Android 在fileoutputstream中存储字符串值
我希望将字符串值存储为文本文件,因此我声明Android 在fileoutputstream中存储字符串值,android,fileoutputstream,Android,Fileoutputstream,我希望将字符串值存储为文本文件,因此我声明 String item1, item2; //code... item1=arraylist.getItem1(); item2=arraylist.getItem2(); FileOutputStream fos; try { fos = openFileOutput(item1, Context.MODE_PRIVATE); fos.write(item2.getBytes()); fos.close(); } catch (FileNotFou
String item1, item2;
//code...
item1=arraylist.getItem1();
item2=arraylist.getItem2();
FileOutputStream fos;
try {
fos = openFileOutput(item1, Context.MODE_PRIVATE);
fos.write(item2.getBytes());
fos.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//code....
但是我得到了一个错误
1)java.lang.illegalargumentexception file contains a path separator
无法打开data/data/my package dir中的我的文本文件,并显示一条
opendir failed permission denied android adb
我在这里做错了什么,以及如何在文本文件中存储和查看字符串的值
1) java.lang.illegalargumentexception文件包含路径分隔符
openFileOutput()不接受路径,只接受文件名。如果要使用路径创建文件,请尝试:
BufferedWriter writer;
try {
File file = new File(filePath);
FileWriter fileWriter = new FileWriter(file);
writer = new BufferedWriter(fileWriter);
...
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
2) opendir失败,权限被拒绝
在android中,您无法访问手机中的文件。如果需要访问该文件,则需要将其保存在可访问的位置,如SD卡。最后,我解决了此问题。我创建了一个新类,并在前一个类中实例化了这个类,我的代码是:
public void Class1(String item1, String item2, Context context)
{
FileOutputStream fos;
try {
fos = context.openFileOutput("newfile.txt", Context.MODE_PRIVATE);
fos.write(item1.getBytes());
fos.write(item2.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
我将这个类实例化为
Class1 main = new Class1();
tracklog.Logger(item1, item2,this);
因此,非法参数异常错误得到解决。希望这可以帮助某人:-)我将fileoutput流移动到一个单独的文件中,并在previpus活动中实例化它,如SecondClass.save(名称、数据);但我还是收到了同样的错误谢谢你的指导:-)