Java IO读写文件


IO流想必大家都比较清楚了,那么如何利用IO流来进行读写文件操作呢,且看如下示例:


首先看如何写文件


创建CreateFile类:



package com.file;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;

public class CreateFile {


public static void main(String[] args) {

FileOutputStream out = null;
FileOutputStream outStr = null;
BufferedOutputStream bufferedOutputStream = null;
FileWriter fw = null;
int count = 1000;// 写文件行数
try {
out = new FileOutputStream(new File("E:/addtest.txt"));
long begin = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
out.write("测试java 文件操作\r\n".getBytes());
}
out.close();
long end = System.currentTimeMillis();
System.out.println("FileOutputStream执行耗时:" + (end - begin) + " 豪秒");
outStr = new FileOutputStream(new File("E:/addtest1.txt"));
bufferedOutputStream = new BufferedOutputStream(outStr);
long begin0 = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
bufferedOutputStream.write("测试java 文件操作\r\n".getBytes());
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
long end0 = System.currentTimeMillis();
System.out.println("BufferedOutputStream执行耗时:" + (end0 - begin0)
+ " 豪秒");
fw = new FileWriter("E:/addtest2.txt");
long begin3 = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
fw.write("测试java 文件操作\r\n");
}
fw.close();
long end3 = System.currentTimeMillis();
System.out.println("FileWriter执行耗时:" + (end3 - begin3) + " 豪秒");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fw.close();
bufferedOutputStream.close();
outStr.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

执行main()就可在E盘中创建addtest.txt文件,同时在该文件中写下千行——测试java 文件操作


下面来看如何读取文件内容:

创建ReadFile类


public class ReadFile {


public static void main(String[] args) {


File a = new File("E:/addtest.txt");
try {
FileInputStream fi = new FileInputStream(a);
InputStreamReader isr = new InputStreamReader(fi, "GBK");
BufferedReader bfin = new BufferedReader(isr);
String rLine = "";
while ((rLine = bfin.readLine()) != null) {
System.out.println(rLine);
}
} catch (IOException e) {
e.printStackTrace();
}


}


}

如此便可以读取E盘中addtest.txt文件中的所有内容


好了,看完以上示例,想必大家应该对IO流如何读写文件有所了解了吧。。。。。。

你可能感兴趣的:(java IO流)