有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java创建文件并将其存储到外部存储器

这可能是一个简单的破解方法,但我不明白为什么这段代码不能在我的Android外部文件系统中创建一个新文件?正确创建了目录,但没有创建文件,取而代之的是java。木卫一。FileNotFoundException:/mnt/sdcard/Mydir/MyFile,有人能看到问题是什么吗?因为我看不到它

        //Generate a unique filename using date and time
    String fileName = "myFile_"+formatter_file_name.format(today)+".txt";

    //Get path to root
    String root = Environment.getExternalStorageDirectory().toString();

    //Create(if not exists) directory in root in which to store the reports 
    File myDir = new File(root + "/myDir");   
    myDir.mkdirs();

    //Create report file object
    File file = new File (myDir, fileName);

    //If file already exists delete id(this should not be able to happen)
    if (file.exists()) file.delete(); 

    try {
        FileOutputStream fout = new FileOutputStream(file);
        OutputStreamWriter osw = new OutputStreamWriter(fout); 

        // Write the string to the file
        osw.write("TEST STRING");

        //Ensure that everything has been written to the file and close 
        osw.flush();
        osw.close();
    } catch (Exception e) {
           e.printStackTrace();
    }    

我在清单中有正确的权限,我将插入一个检查,看看外部存储是否可用于写入,但我不认为这是问题所在


共 (1) 个答案

  1. # 1 楼答案

    试试这个

    try {
       File root = Environment.getExternalStorageDirectory();
       File myFile = new File(root +"/textfile.txt");
       myFile.createNewFile();
    
       FileOutputStream fOut = new FileOutputStream(myFile);
       OutputStreamWriter myOutWriter = 
             new OutputStreamWriter(fOut);
       myOutWriter.append("String entered in file");
    
       myOutWriter.close();
       fOut.close();
    } catch (Exception e) {
       Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
    
    }