Android 文件读写的例子

时间:2022-12-24 17:08:38
 import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.http.util.EncodingUtils; public class MyLogFile {
private static FileOutputStream fout;
public MyLogFile() {
} public static void createFile(){
try {
fout = new FileOutputStream("/mnt/sdcard/zyrPad.txt");
// fout = openFileOutput("/mnt/sdcard/zyrPad.txt",Mode);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} //写在/mnt/sdcard/目录下面的文件
public static void writeFileSdcard(String message){
try{
//FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);
message= message+"\n";
byte [] bytes = message.getBytes();
fout.write(bytes);
} catch(Exception e){
e.printStackTrace();
}
} //读在/mnt/sdcard/目录下面的文件
public String readFileSdcard(String fileName){
String res="";
try{
FileInputStream fin = new FileInputStream(fileName);
int length = fin.available();
byte [] buffer = new byte[length];
fin.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
fin.close();
} catch(Exception e){
e.printStackTrace();
}
return res;
} /** * 关闭文件流 */
public static void closeFile(){
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

调用的时候很简单:
MyLogFile.createFile();//创建文件
MyLogFile.writeFileSdcard("------------写文字到文件中----------------");

使用完后,记得关闭:
MyLogFile.closeFile()