博主平时用Python比较多,最近因为工作需要使用Java编程,比较之下,发现Python读写文件真是太方便了!Java读写文件非常繁琐,简直让人抓狂!
Python读写文件的语句
- 读文件
- with open('readFile', 'r') as inFile:
- for line in inFile.readlines():
- print line
- ...
- 写文件
- with open('writeFile', 'w') as outFile:
- outFile.write("...")
- 从标准输入读取
- import sys
- for line in sys.stdin:
- print line
- ...
- 输出到标准输出
- print "..."
- ~
Java读写文件的语句
Java读写文件需要编程者了解读写文件的原理,例如输入流、输出流、读写缓冲等,好处是使用者知道读写原理,弊端就是写起来比较繁琐,不容易掌握。
- import java.io.InputStreamReader;
- import java.io.FileInputStream;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.BufferedWriter;
- import java.io.File;
- BufferedReader br1 = new BufferedReader(new InputStreamReader(new FileInputStream("read_file1")));
- BufferedReader br2 = new BufferedReader(new FileReader("read_file2"));
- String line = null;
- while((line = br1.readLine())!=null){
- System.out.println(line);
- ...
- }
- File outfile = new File("write_file");
- if (!file.exists()){
- file.createNewFile();
- }
- //true = append file
- FileWriter fileWritter = new FileWriter(file.getName(),true);
- BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
- bufferWritter.write(data);
- bufferWritrer.flush();//缺少这一句很可能不能将内容写到文件中,内容一直呆在缓冲区
- bufferWritter.close();