1. FileWriter FileReader 用字符流来读写文写,一次性读取2个字节
public static void main(String[] args){
File f = new File("d:\\dmeo.txt");
String s = "I Am Learning Java,我正在学习Java";
//将数据写入文件
try {
FileWriter write = new FileWriter(f);
write.write(s); //可以直接转入字符串
write.flush();
write.close();
} catch (IOException e) {
e.printStackTrace();
}
//读取数据
try {
FileReader reader = new FileReader(f);
char[] c = new char[(int) f.length()];
for (int i = 0; i < c.length; i++) {
c[i] = (char)reader.read(); //将读出的数据转为字符
}
reader.close();
System.out.println(new String(c));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
2.BufferedReader 、 BufferedWriter
public static void main(String[] args){
//写数据
File f = new File("D:\\demo.txt");
String s = "I Am Learning Java" + "\r\n" + "我正在学习Java";
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write(s);
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
//读数据
try {
BufferedReader br = new BufferedReader(new FileReader(f));
String str = null;
while((str = br.readLine())!=null) {
System.out.println(str);
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

551

被折叠的 条评论
为什么被折叠?



