Java之文件的读写操作
package com.example;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;;
public class MainActivity {
public static void main (String[] args){
try{
/* 读入文件内容 */
String pathname = "C:\\Users\\lzl\\Desktop\\aa.txt"; //获取文件的绝对路径
File filename = new File(pathname);
InputStreamReader reader = new InputStreamReader(new FileInputStream(filename));
BufferedReader br = new BufferedReader(reader);
String line = "";
while((line = br.readLine()) != null){ //一次读入一行,判断条件很关键
System.out.println(line);
}
/* 写入文件内容 */
File file = new File("C:\\Users\\lzl\\Desktop\\bb.txt");
file.createNewFile();
BufferedWriter bw = new BufferedWriter(new FileWriter(file)); //
bw.write("test\r\ntest\r\n"); //\r\n即为换行
bw.flush(); //把缓存区的内容转到文件中
bw.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
注意在读取文件中的内容时当采用以下方法会导致不能读取文件中的最后一行。
line = br.readLine();
while(line != null){
line = br.readLine();
System.out.println(line);
}
Android之文件读写操作
Android之文件读操作
public String load(){
FileInputStream in = null;
BufferedReadr br = null;
StringBuilder content = new StringBuilder();
try{
in = openFileStream("XX"); //读取文件
br = new BufferedReader(new InputStreamReader(in));
String line = "";
while((line = br.readline()) != null){ //这条与语句很重要
content.append(line);
}
}catch(IOException e){
e.printStackTrace();
} finally{
try{
if(bw != null){
br.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
return content.toString();
}
Android之文件写操作
public void save(){
String data = "XX";
FileOutputStream fos = null;
try{
fos = openFileOutput("data" , Context.MODE_PRIVATE);
OutputStreamWriter out = new OutputStreamWriter(fos);
BufferedWiter bw = new BufferedWriter(out);
bw.write(data);
}catch(IOException e){
e.printStackTrace();
} finally{
try{
if(bw != null){
br.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
关键的区别在于,Android的自己的文件存储位置,通过openFileStream自动的定位,而Java中是通过pathname来获取绝对路径。