读取写入:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Test1 {
public static void main(String[] args) {
try {
int linenum=0;
FileReader fr=new FileReader("E:\\java\\javatest\\NewFile.txt");
BufferedReader br=new BufferedReader(fr);
BufferedWriter bw=new BufferedWriter(new FileWriter("E:\\java\\javatest\\targetFile.txt"));
String s=br.readLine();
while(s!=null)
{
linenum++;
bw.write(linenum+" ");
bw.write(s);
bw.newLine();
s=br.readLine();
}
bw.close();
br.close();
System.out.println("文件保存结束...");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
读取:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class Test0 {
public static void main(String[] args) {
try {
FileReader fr=new FileReader("E:\\java\\javatest\\NewFile.txt");
BufferedReader br=new BufferedReader(fr);
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
String s=br.readLine();
while(s!=null)
{
bw.write(s);
bw.newLine();
s=br.readLine();
}
br.close();
bw.close();
System.out.println("文件读取成功..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}