当前位置: 代码网 > it编程>编程语言>Java > Java文件操作和IO示例详解

Java文件操作和IO示例详解

2024年12月26日 Java 我要评论
java中通过java.io.file类来对一个文件(包括目录)进行抽象的描述.注意,有file对象,并不代表真实存在该文件.一、file概述file类的构造方法有四种重载方式,通常使用如下:file

java中通过java.io.file类来对一个文件(包括目录)进行抽象的描述.注意,有file对象,并不代表真实存在该文件.

一、file概述

file类的构造方法

有四种重载方式,通常使用如下:

file(string pathname) //指定文件(或目录)名和路径创建文件对象

file file =new file("hello.text");  //在当前目录创建文件对象

file file =new file("java"); //在当前目录创建一个目录对象

file file=new file("d:\\java");  //指明详细的路径以及目录名,请注意双斜线

方法

代码示例

示例1:观察get系列的观点与差异:

import java.io.file;
import java.io.ioexception;
public class main {
    public static void main(string[] args) throws ioexception {
        file file = new file("..\\hello-world.txt"); // 并不要求该文件真实存在
        system.out.println(file.getparent());
        system.out.println(file.getname());
        system.out.println(file.getpath());
        system.out.println(file.getabsolutepath());
        system.out.println(file.getcanonicalpath());
   }
}

运行结果

..

hello-world.txt

..\hello-world.txt

d:\代码练习\文件示例1\..\hello-world.txt

d:\代码练习\hello-world.txt

示例2 普通文件的创建、删除

import java.io.file;
import java.io.ioexception;
public class main {
    public static void main(string[] args) throws ioexception {
        file file = new file("hello-world.txt"); // 要求该文件不存在,才能看到相同
的现象
        system.out.println(file.exists());
        system.out.println(file.isdirectory());
        system.out.println(file.isfile());
        system.out.println(file.createnewfile());
        system.out.println(file.exists());
        system.out.println(file.isdirectory());
        system.out.println(file.isfile());
        system.out.println(file.createnewfile());
   }
}

运行结果 

false

false

false

true

true

false

true

false

示例3 普通文件的删除 

import java.io.file;
import java.io.ioexception;
public class main {
    public static void main(string[] args) throws ioexception {
        file file = new file("some-file.txt"); // 要求该文件不存在,才能看到相同的现
象
        system.out.println(file.exists());
        system.out.println(file.createnewfile());
        system.out.println(file.exists());
        system.out.println(file.delete());
        system.out.println(file.exists());
   }
}

运行结果

false

true

true

true

false

示例4 观察 deleteonexit 的现象 

import java.io.file;
import java.io.ioexception;
public class main {
    public static void main(string[] args) throws ioexception {
        file file = new file("some-file.txt"); // 要求该文件不存在,才能看到相同的现
象
        system.out.println(file.exists());
        system.out.println(file.createnewfile());
        system.out.println(file.exists());
        file.deleteonexit();
        system.out.println(file.exists());
   }
}

示例5  观察目录的创建

import java.io.file;
import java.io.ioexception;
public class main {
    public static void main(string[] args) throws ioexception {
        file dir = new file("some-dir"); // 要求该目录不存在,才能看到相同的现象
        system.out.println(dir.isdirectory());
        system.out.println(dir.isfile());
        system.out.println(dir.mkdir());
        system.out.println(dir.isdirectory());
        system.out.println(dir.isfile());
   }
}

运行结果

false

false

true

true

false

示例6  观察目录创建2

import java.io.file;
import java.io.ioexception;
public class main {
    public static void main(string[] args) throws ioexception {
        file dir = new file("some-parent\\some-dir"); // some-parent 和 somedir 都不存在
        system.out.println(dir.isdirectory());
        system.out.println(dir.isfile());
        system.out.println(dir.mkdir());
        system.out.println(dir.isdirectory());
        system.out.println(dir.isfile());
   }
}

运行结果

false

false

false

false

false

mkdir() 的时候,如果中间目录不存在,则无法创建成功; mkdirs() 可以解决这个问题 

import java.io.file;
import java.io.ioexception;
public class main {
    public static void main(string[] args) throws ioexception {
        file dir = new file("some-parent\\some-dir"); // some-parent 和 somedir 都不存在
        system.out.println(dir.isdirectory());
        system.out.println(dir.isfile());
        system.out.println(dir.mkdirs());
        system.out.println(dir.isdirectory());
        system.out.println(dir.isfile());
   }
}

 运行结果

false

false

true

true

false

示例7  观察文件重命名.

import java.io.file;
import java.io.ioexception;
public class main {
    public static void main(string[] args) throws ioexception {
        file file = new file("some-file.txt"); // 要求 some-file.txt 得存在,可以
是普通文件,可以是目录
        file dest = new file("dest.txt");   // 要求 dest.txt 不存在
        system.out.println(file.exists());
        system.out.println(dest.exists());
        system.out.println(file.renameto(dest));
        system.out.println(file.exists());
        system.out.println(dest.exists());
   }
}

运行结果 

true

false

true

false

true

 二、文件内容的读写 —— 数据流 

输入流(inputstream)概述.

方法

修饰符及

返回值类

方法签名

说明

int

read()

读取一个字节的数据,返回 -1 代表已经完全读完了

int

read(byte[] b)

最多读取 b.length 字节的数据到 b 中,返回实际读到的数量;-1 代表以及读完了

int

read(byte[] b,

int off, int len)

最多读取 len - off 字节的数据到 b 中,放在从 off 开始,返

回实际读到的数量; -1 代表以及读完了

void

close()

关闭字节流

inputstream 只是一个抽象类,要使用还需要具体的实现类。关于 inputstream 的实现类有很多,基本可以认为不同的输入设备都可以对应一个 inputstream 类,我们现在只关心从文件中读取,所以使用 fileinputstream

利用fileinputstream 从文件中读取

构造方法

签名说明

fileinputstream(file file)

利用 file 构造文件输入流

fileinputstream(string name)

利用文件路径构造文件输入流

代码示例

示例1

将文件完全读完的两种方式。相比较而言,后一种的 io 次数更少,性能更好

import java.io.*;
// 需要先在项目目录下准备好一个 hello.txt 的文件,里面填充 "hello" 的内容
public class main {
    public static void main(string[] args) throws ioexception {
        try (inputstream is = new fileinputstream("hello.txt")) {
            while (true) {
                int b = is.read();
                if (b == -1) {
                    // 代表文件已经全部读完
                    break;
               }
                
                system.out.printf("%c", b);
           }
       }
   }
}
import java.io.*;
// 需要先在项目目录下准备好一个 hello.txt 的文件,里面填充 "hello" 的内容
public class main {
    public static void main(string[] args) throws ioexception {
        try (inputstream is = new fileinputstream("hello.txt")) {
            byte[] buf = new byte[1024];
            int len;
            
            while (true) {
                len = is.read(buf);
                if (len == -1) {
                    // 代表文件已经全部读完
                    break;
               }
                
                for (int i = 0; i < len; i++) {
               system.out.printf("%c", buf[i]);
               }
           }
       }
   }
}

示例2

这里我们把文件内容中填充中文看看,注意,写中文的时候使用 utf-8 编码。 hello.txt 中填写 " 你好中国"

注意:这里我利用了这几个中文的 utf-8 编码后长度刚好是 3 个字节和长度不超过 1024 字节的现状,但这种方式并不是通用的

import java.io.*;
// 需要先在项目目录下准备好一个 hello.txt 的文件,里面填充 "你好中国" 的内容
public class main {
    public static void main(string[] args) throws ioexception {
        try (inputstream is = new fileinputstream("hello.txt")) {
            byte[] buf = new byte[1024];
            int len;
            while (true) {
                len = is.read(buf);
                if (len == -1) {
                    // 代表文件已经全部读完
                    break;
               }
                // 每次使用 3 字节进行 utf-8 解码,得到中文字符
                // 利用 string 中的构造方法完成
                // 这个方法了解下即可,不是通用的解决办法
                for (int i = 0; i < len; i += 3) {
                    string s = new string(buf, i, 3, "utf-8");
                    system.out.printf("%s", s);
               }
           }
       }
   }
}

利用 scanner 进行字符读取

上述例子中,我们看到了对字符类型直接使用 inputstream 进行读取是非常麻烦且困难的,所以,我们使用一种我们之前比较熟悉的类来完成该工作,就是 scanner 类。

构造方法说明

scanner(inputstream is, string charset)

使用 charset 字符集进行 is 的扫描读取

import java.io.*;
import java.util.*;
// 需要先在项目目录下准备好一个 hello.txt 的文件,里面填充 "你好中国" 的内容
public class main {
    public static void main(string[] args) throws ioexception {
        try (inputstream is = new fileinputstream("hello.txt")) {
           try (scanner scanner = new scanner(is, "utf-8")) {
               while (scanner.hasnext()) {
                   string s = scanner.next();
                   system.out.print(s);
               }
           }
       }
   }
}

输出流outputstream 概述

方法

修饰 符及 返回 值类 

方法签名

说明

void

write(int b)

写入要给字节的数据

void

write(byte[] b)

将 b 这个字符数组中的数据全部写入 os 中

int

write(byte[] b, int off, int len)

将 b 这个字符数组中从 off 开始的数据写入 os 中,一共写 len 个

void

close()

关闭字节流

void

flush()

重要:我们知道 i/o 的速度是很慢的,所以,大多的 outputstream 

了减少设备操作的次数,在写数据的时候都会将数据先暂时写入内存的

一个指定区域里,直到该区域满了或者其他指定条件时才真正将数据写 入设备中,这个区域一般称为缓冲区。但造成一个结果,就是我们写的

数据,很可能会遗留一部分在缓冲区中。需要在最后或者合适的位置,

调用 flush (刷新)操作,将数据刷到设备中。

outputstream 同样只是一个抽象类,要使用还需要具体的实现类。我们现在还是只关心写入文件中,所以使用 fileoutputstream

利用 outputstreamwriter 进行字符写入 

示例1

import java.io.*;
public class main {
    public static void main(string[] args) throws ioexception {
        try (outputstream os = new fileoutputstream("output.txt")) {
            os.write('h');
            os.write('e');
            os.write('l');
            os.write('l');
            os.write('o');
            // 不要忘记 flush
            os.flush();
       }
   }
}

示例2

import java.io.*;
public class main {
    public static void main(string[] args) throws ioexception {
        try (outputstream os = new fileoutputstream("output.txt")) {
            byte[] b = new byte[] {
               (byte)'g', (byte)'o', (byte)'o', (byte)'d'
           };
            os.write(b);
          
            // 不要忘记 flush
            os.flush();
       }
   }
}

示例3

import java.io.*;
public class main {
    public static void main(string[] args) throws ioexception {
        try (outputstream os = new fileoutputstream("output.txt")) {
            byte[] b = new byte[] {
               (byte)'g', (byte)'o', (byte)'o', (byte)'d', (byte)'b', 
(byte)'a', (byte)'d'
           };
            os.write(b, 0, 4);
          
            // 不要忘记 flush
            os.flush();
       }
   }
}

示例4

import java.io.*;
public class main {
    public static void main(string[] args) throws ioexception {
        try (outputstream os = new fileoutputstream("output.txt")) {
           string s = "nothing";
            byte[] b = s.getbytes();
            os.write(b);
          
            // 不要忘记 flush
            os.flush();
       }
   }
}

示例5

import java.io.*;
public class main {
    public static void main(string[] args) throws ioexception {
        try (outputstream os = new fileoutputstream("output.txt")) {
            string s = "你好中国";
            byte[] b = s.getbytes("utf-8");
         os.write(b);
            // 不要忘记 flush
            os.flush();
       }
   }
}

利用 printwriter 输出 

上述,我们其实已经完成输出工作,但总是有所不方便,我们接来下将 outputstream 处理下,使用

printwriter 类来完成输出,因为

printwriter 类中提供了我们熟悉的 print/println/printf 方法

outputstream os = ...;
outputstreamwriter oswriter = new outputstreamwriter(os, "utf-8"); // 告诉它,我
们的字符集编码是 utf-8 的
printwriter writer = new printwriter(oswriter);
// 接下来我们就可以方便的使用 writer 提供的各种方法了
writer.print("hello");
writer.println("你好");
writer.printf("%d: %s\n", 1, "没什么");
// 不要忘记 flush
writer.flush();

 示例1

import java.io.*;
public class main {
    public static void main(string[] args) throws ioexception {
        try (outputstream os = new fileoutputstream("output.txt")) {
            try (outputstreamwriter oswriter = new outputstreamwriter(os, "utf-
8")) {
                try (printwriter writer = new printwriter(oswriter)) {
                    writer.println("我是第一行");
                    writer.print("我的第二行\r\n");
                    writer.printf("%d: 我的第三行\r\n", 1 + 1);
                    writer.flush();
               }
           }
       }
   }
}

总结 

到此这篇关于java文件操作和io的文章就介绍到这了,更多相关java文件操作和io内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com