我的代码无效,因为files == null
并在我尝试加载文件时崩溃所以我认为它不会创建目录。
当我点击保存时,Toast消息File Created显示。
我认为它正在输出正确的道路。
Path: /data/data/com.example.tiagosilva.amob_android/files/OperationLists/
btn_saveOperationList.setOnClickListener(new View.OnClickListener() {
String mText = "";
String n,x,y,z,r;
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setTitle("Save the File");
final EditText fileName = new EditText(v.getContext());
fileName.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(fileName);
builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mText = fileName.getText().toString();
FileOutputStream fileOutputStream;
File file = new File(getContext().getFilesDir() +"/OperationLists/",mText);
Log.d("Files","Path: " + getContext().getFilesDir() +"/OperationLists/");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try
{
fileOutputStream = getContext().openFileOutput(mText, Context.MODE_PRIVATE);
for(int i=0;i<lv_operationList.getAdapter().getCount() -1;i++)
{
fileOutputStream.write(lv_operationList.getAdapter().toString().getBytes());
}
Toast.makeText(getActivity().getBaseContext(), "File Created",
Toast.LENGTH_LONG).show();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
});
btn_loadOperationList.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<String> fileList = new ArrayList<String>();
String path = getContext().getFilesDir() + "/OperationLists/";
Log.d("Files","Path: " +path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files","Size: " +files.length);
if(files != null) {
for (int i = 0; i < files.length; i++) {
fileList.add(files[i].getName());
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, fileList);
lv_listFiles.setAdapter(directoryList);
}
}
});
答案 0 :(得分:0)
可以在清单文件中添加WRITE_EXTERNAL_STORAGE和READ_EXTERNAL_STORAGE权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
答案 1 :(得分:0)
尝试替换
文件文件=新文件(getContext()。getFilesDir()+&#34; / OperationLists /&#34;,mText);
用这个
文件文件=新文件(getContext()。getFilesDir()。getAbsolutePath()+&#34; / OperationLists /&#34;,mText);