我一直试图制作一款使用手机内存储存的应用。 这就是我的方法:
public void writeToFile(String data,String name, Context context) {
try {
FileOutputStream fos = openFileOutput(name, Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
当我尝试使用writeToFile方法时,应用程序崩溃。
[编辑]
我对你来说有点新意,这就是你的意思吗?
08-20 17:32:04.301 921-921/com.adamcomp.websitecreator E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.adamcomp.websitecreator, PID: 921
java.lang.IllegalArgumentException: File android.support.v7.widget.AppCompatEditText{5211a9d VFED..CL. .F...... 150,514-570,605 #7f0d007c app:id/prjname}_code.txt contains a path separator
at android.app.ContextImpl.makeFilename(ContextImpl.java:2322)
at android.app.ContextImpl.openFileOutput(ContextImpl.java:466)
at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:197)
at com.adamcomp.websitecreator.NewProject.writeToFile(NewProject.java:75)
at com.adamcomp.websitecreator.NewProject$1.onClick(NewProject.java:60)
at android.view.View.performClick(View.java:5721)
at android.widget.TextView.performClick(TextView.java:10949)
at android.view.View$PerformClick.run(View.java:22624)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7407)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
答案 0 :(得分:0)
java.lang.IllegalArgumentException: File android.support.v7.widget.AppCompatEditText{5211a9d VFED..CL. .F...... 150,514-570,605 #7f0d007c app:id/prjname}_code.txt contains a path separator
您似乎正在传递toString()
EditText
作为文件名,此字符串表示包含无效字符。
相反,要在EditText
中获取文字内容,请致电getText()
以获取Editable
并在其上调用toString()
。所以,如果你现在有
editText.toString()
将其更改为
editText.getText().toString()
答案 1 :(得分:-1)
如果您尝试将文件保存在数据目录中,请尝试此操作:
public void save(String data, String folder, String fileName, Context c) {
File Folder = new File(c.getFilesDir() + File.separator + folder);
if (!Folder.mkdir()) {
}
//Make sure not to include a path separator("/")
//Just enter the path name.
//e.g If you want to store the file in a folder named myFolder, and you file name is myFile
//Then use the function like this: save(your data,"myFolder","myFile",context);
File file = new File(c.getFilesDir() + File.separator
+ folder + File.separator + fileName);
try {
if (!file.createNewFile()) {
}
OutputStream osw = new FileOutputStream(file, true);
osw.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
答案 2 :(得分:-2)
也许你有问题,
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
您正在使用Exception尝试使用IOException