Java中的文件输入输出操作比较麻烦,初学时很难理得清楚。
最近自己在看Java的书,想把自己理解的想法分享一下,也希望大家能指出哪里有理解不正确的地方。
在Java中文件的读取使用流的方式,分为:1)字节流;2)字符流。
还有一种比较方便的读取方式(Scanner),放在后边再说。
1、字节流的读取
import java.io.*;
public class BufferedByteType {
public static void main(String[] args) {
/**
* 使用“字节流”的方式读取与写入文件
* 可用于处理图像数据等,非文本文件的数据
* 基础是:InputStream & OutputStream
*/
try{
File fin = new File("E:/in.bmp");//输入图像数据
FileInputStream fis = new FileInputStream(fin); //以字节流的方式读取文件,不带缓冲区
BufferedInputStream bis = new BufferedInputStream(fis);//使用缓冲读取文件字节流
File fout = new File("E:/out.bmp");//输出图像数据
FileOutputStream fos = new FileOutputStream(fout);//以字节流的方式写入文件,不带缓冲区
BufferedOutputStream bos = new BufferedOutputStream(fos);//使用缓冲写入文件字节流
byte[] buf = new byte[128]; //每次最多读取128个字节,在运用中会很大
for(int len = bis.read(buf, 0, buf.length) ; //初始读取文件
len != -1 ; //文件读取结束,返回-1
len = bis.read(buf, 0, buf.length) //读取文件的下一区域
){
bos.write(buf, 0, len); //写入文件,注意这里的长度是len,而不是buf.length
}
//关闭操作
bis.close();
bos.close();
}catch(IOException e){
e.printStackTrace();
System.exit(0);
}
}
}
2、字符流的读取
import java.io.*;
public class BufferedCharType {
public static void main(String[] args) {
/**
* 使用“字符流”的方式读取与写入文件
* 可用于处理文本文件数据
* ps:若用来处理图像等非文本文件数据时,会有很多问题,应使用字节流的方式
* 基础是:Reader & Writer
*/
try{
File fin = new File("E:/in.txt");//输入文本文件
FileReader fr = new FileReader(fin); //以字符流的方式读取文件,不带缓冲区
BufferedReader br = new BufferedReader(fr);//使用缓冲读取文件字节流
File fout = new File("E:/out.txt");//输出文本文件
FileWriter fw = new FileWriter(fout);//以字符流的方式写入文件,不带缓冲区
BufferedWriter bw = new BufferedWriter(fw);//使用缓冲写入文件字符流
char[] buf = new char[3]; //每次最多读取3个字符,在运用中会很大
for(int len = br.read(buf, 0, buf.length) ; //初始读取文件
len != -1 ; //文件读取结束,返回-1
len = br.read(buf, 0, buf.length) //读取文件的下一区域
){
bw.write(buf, 0, len); //写入文件,注意这里的长度是len,而不是buf.length
}
//关闭操作
br.close();
bw.close();
}catch(IOException e){
e.printStackTrace();
System.exit(0);
}
}
}
/**
* 测试文件 in.txt
*
* 1 2 3
* 4 5
* 6
* 7
* 8 9
* abc de f
* gh i
* j
* k
* l
* m n p
*
* 输出文件 out.txt
*
* 1 2 3
* 4 5
* 6
* 7
* 8 9
* abc de f
* gh i
* j
* k
* l
* m n p
*
*/
3、使用Scanner读取
使用Scanner可以很很方便的从文件或键盘读入数据,使用很简单
import java.io.*;
import java.util.Scanner;
public class ScannerType {
public static void main(String[] args){
/**
* 使用Scanner可以很方便的从文件或键盘读入数据
* 比较方便在程序比赛中使用,当然完成老师作业跟不在话下
*/
Scanner sc = null;
//sc = new Scanner(System.in);// 从标准输入设备(键盘)读取数据
try{
sc = new Scanner(new File("E:/test.txt")); // 从文件中读取数据
}catch(FileNotFoundException e){
e.printStackTrace();
System.exit(0);
}
while(sc.hasNext()){ //当读取到文件结尾(EOF)时会跳出循环
System.out.println(sc.next());//按分割符号读取数据,默认为(空格 和 回车)
}
sc.close();//关闭操作
}
}
/**
* 测试文件 test.txt
*
* 1 2 3
* 4 5
* 6
* 7
* 8 9
*
* 输出
*
* 1
* 2
* 3
* 4
* 5
* 6
* 7
* 8
* 9
*
*/