File
创建一个文件对象。
1 2 3 4 5
| File file = new File("1.txt");
if(!file.exists()) file.createNewFile();
file.delete();
|
只提供对字节和字节数组的读取方法。 不是很适合处理汉字。 汉字占两个字节。
1 2 3 4 5 6 7
| File file = new File();
FileOutputStream out = new FileOutputStream(file); byte msg[]="".getBytes(); out.write(msg); out.close();
|
1 2 3 4 5
| FileInputStream in = new FileInputStream(file); byte msg[] = new byte[1024]; int len = in.read(msg); String content = new String(msg, 0, len); in.close();
|
FileReader FileWriter
FileWriter
似乎可以直接输出字符串对象, FileReader
用法可以和 FileInputStream
一样。 问题搁置。
1 2 3 4
| FileWriter out = new FileWriter(); String s; out.write(s); out.close();
|
BufferedReader BufferedWriter
可以读写字符和字符串。
可以使用FileReader和FileWriter构造。
read()
单个字符
readLine()
write(String s)
newLine()
输出一个换行符
RandomAccessFile
1 2 3 4 5
| RandomAccessFile raf = new RandomAccessFile("Lunch.java", "r"); String str; while((str = raf.readLine()) != null) { list.add(str); }
|
(未测试, 应该是有错误)
1 2 3 4 5 6
| ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("persons.txt")); out.writeObject(list); out.close(); ObjectInputStream in = new ObjectInputStream(new FileInputStream("person.txt")); Collection<Person> list1 = (ArrayList) in.readObject();
|