1.例:
public class JavaFile {
public static void main(String[] args) {
try {
// read file content from file
StringBuffer sb= new StringBuffer("");
FileReader reader = new FileReader("c://test.txt");
BufferedReader br = new BufferedReader(reader);
String str = null;
while((str = br.readLine()) != null) {
sb.append(str+"/n");
System.out.println(str);
}
br.close();
reader.close();
// write string to file
FileWriter writer = new FileWriter("c://test2.txt");
BufferedWriter bw = new BufferedWriter(writer);
bw.write(sb.toString());
bw.close();
writer.close();
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
2.例:
File fr=null;
fr = new File("c:/test/test1.txt");// 建立FileReader对象,并实例化为fr
InputStreamReader isr = new InputStreamReader (new FileInputStream(fr),"GBK");// 建立BufferedReader对象,并实例化为br 控制读取乱码
BufferedReader br = new BufferedReader(isr);
String line=null;
line = br.readLine(); // 从文件读取一行字符串
while (line != null) {
System.out.println(line);
}