我正在尝试将文本文件写入内部存储,并想知道最好的方法是什么,文本文件将包含字符串。
我有:
File file = new File(getFilesDir() + subFolderName + "/" + fileName);
BufferedWriter writer;
try {
writer = new BufferedWriter(new FileWriter(file));
writer.write("ID, Date, Address, Body");
writer.write("\n");
for (String s : list) {
writer.write(s);
writer.write("\n");
}
writer.write("\n");
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
我在创建新文件时得到java.lang.NullPointerException
:/
提前致谢。
这是我最终得到的代码,它按照我的意愿工作:
public void WriteFileInternal(ArrayList<String> list, String FileName, Context context) {
BufferedWriter bw;
try {
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("SMSMonitor", Context.MODE_PRIVATE);
if (!directory.exists()){
directory.createNewFile();
directory.mkdir();
}
File file = new File(directory +"/"+ FileName);
file.createNewFile();
bw = new BufferedWriter(new FileWriter(file));
bw.write("ID, Date, Body, Phone Number");
bw.write("\n");
for (String s1 : list) {
bw.write(s1);
bw.write("\n");
}
bw.write("\n");
bw.flush();
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
我有这种方法来存储有关用户和密码的信息(仍然需要编写,但你可以使用它作为基础)
public void saveUserData(String user, String password){
FileOutputStream fos;
DataOutputStream dos;
try {
File f = this.getFilesDir();
String s = f.getCanonicalPath();
File file= new File(s + "/user.txt");
if(file.exists()){
file.delete();
}
file.createNewFile();
fos = new FileOutputStream(file);
dos = new DataOutputStream(fos);
dos.write(user.getBytes());
dos.writeChars("\n");
dos.write(password.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
答案 1 :(得分:0)
package com.file;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
public class FileWrite extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}