Java:文件读写IO操作

//文件读写:
BufferedReader reader = new BufferedReader(new FileReader(new File("file.in")));
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("file.out")));

//其中FileReader和FileWriter可以无缓冲区的读写,
//BufferedReader 和BufferedWriter  是加入缓冲区。
reader.readLine();  //到达流末尾返回null , .trim()可一忽略前导空白和尾部空白
writer.write(...);


//写字符串可以用PrintWriter方法,更简单,如:
PrintWriter out = new PrintWriter("file.out");
out.println("Hello World");
out.close();


//对象读写(对象序列化,需要实现Serializable接口):
ObjectInputStream is = new ObjectInputStream(new FileInputStream(new File("file.in"))) ;
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(new File("file.out"))) ;
is.readObject(); //每次调用返回下一个对象,需要强制转换后使用
os.writeObject(Object);

//如读写编码为ANSI的文件: 
is = new FileInputStream( new File("file.in") );
BufferedReader reader = new BufferedReader(  new InputStreamReader(is , "GBK")  );

//File类包含文件和目录信息,里面能获取文件名,目录子目录等一些操作。


//另外一种读取方式:
import java.util.Scanner;
Scanner reader = new Scanner(new File("file.in"));
reader.hasNext...();
reader.next...();
posted @ 2018-12-08 20:12  xuejianbest  阅读(287)  评论(0编辑  收藏  举报