java文件操作
1.文件操作的基本流程: 1、 通过File类找到一个文件 2、 通过File类去实例化字节流、字符流操作类 3、 进行读或写的操作,在写的时候如果文件不存在则会自动创建 4、 关闭流并释放资源
2.字节流 在字节流中分为两种: 输出流:OutputStream 输入流:InputStream
2.1 输出流 定义:abstract class OutputStream extends Object implements Closeable, Flushable |-OutputStream子类:FileOutputStream |-构造方法:public FileOutputStream(File file) 输出方法: void write(byte b) 将 b.length 个字节从指定的字节数组写入此输出流 需要将一个字符串变为一个byte数组,通过方法:public byte getBytes() 将String转化成byte。 关闭流:void close() 关闭此输出流并释放与此流有关的所有系统资源。 例1.程序如下:(代码没有优化,只为实现效果)
// 1.通过File找到一个文件
File file = new File("e:\\hello.txt");
try {
// 2.通过子类实例化
OutputStream out = new FileOutputStream(file);
String str = "Hello World!!!!";
byte b[] = str.getBytes();
// 3.写操作
out.write(b);
// 4.关闭流
//out.close();
} catch (Exception e) {}
2.2 输入流 使用InputStream读取内容。 InputStream也是一个抽象类,所以必须使用其子类:FileInputStream 读的方式: int read(byte b) 从输入流中读取一定数量的字节并将其存储在缓冲区数组 b 中。 |- 传入一个byte数组,将所有的内容保存在byte数组之中。 |- 此方法返回向数组中写入数据的个数 将byte数组变为字符串:public String(byte b)、public String(byte b,int be,int len) 例2.
File file = new File("e:\\hello.txt") ;
try {
// 通过子类实例化
InputStream input = new FileInputStream(file);
byte b[] = null;
int len = 0;
b = new byte[1024];//
// 把所有的内容读到数组b中
// 返回读取的个数
len = input.read(b);
input.close();
System.out.println(new String(b, 0, len));
} catch (Exception e) {}
在读取文件的时候,我们需要设置byte的长度,如果大了,那么空间就会浪费,至于如何根据文件大小设置 长度,将b = new byte;替换成 b = new byte ;就行了。
3.字符流 一个字符 = 两个字节。 在字符流操作中,主要使用以下两个类: 字符输出流:Writer 字符输入流:Reader
3.1 字符输出流 写字符串: void write(String str) 写入字符串。 例3.
try {
// 通过子类实例化
Writer out = new FileWriter(new File("e:\\hello.txt"));
String str = "Hello World!!!!!";
out.write(str);
out.close();
} catch (Exception e) {}
3.2 字符输入流 读的方法: |- int read(char cbuf) 将字符读入数组。 |- int read() 读取单个字符。 例4.
try {
// 通过子类实例化
Reader input = new FileReader(file);
char c[] = null;
int len = 0;
c = new char[(int) file.length()];
len = input.read(c);
System.out.println(new String(c, 0, len));
input.close();
} catch (Exception e) {}
4. 字节流和字符流的区别 所有的文件不管是使用Output、Writer实际上最终保存在文件上的都是字节。字符是在内存中形成的。 例如将例1中的out.close();注释掉,表示不关闭输出流。
// 1.通过File找到一个文件
File file = new File("e:\\hello.txt") ;
// 2. 输出流操作类
OutputStream out = null;
try {
// 2.通过子类实例化
out = new FileOutputStream(file);
String str = "Hello World!!!";
byte b = str.getBytes();
// 3.写操作
out.write(b);
// 4.关闭流
<span style="color:violet">//out.close();</span>
}catch (Exception e) {}
我们观察到字符串依然写到文件里,证明字节流是直接操作文件本身的。再看字符流的输出,我们将程序例3 的关闭流语句注释了,运行之后,发现文件虽然创建,但是内容并没有写进去,这是因为对于字符流在关闭操 作的时候,会强制性的将缓存清空,那么以上代码并没有关闭,所以现在的内容还在缓存里,并没有直接到文 件之中。想如何在不关闭流的情况下写文件呢? 在Writer类中提供了一个强制性清空缓存的操作: abstract void flush() 刷新此流。 将out.close();替换为 out.flush() ;