【问题标题】:Error reading a txt file读取 txt 文件时出错
【发布时间】:2018-08-24 22:52:17
【问题描述】:

当我尝试读取保存在手机外部存储上的文件时,我的代码中出现此错误:

java.io.FileNotFoundException: shopping.txt: open failed: ENOENT (No such file or directory)

我可以成功地将数据写入这个文件,我做了很多次。 但是,我无法访问以读取同一个文件、提供整个路径或通过其他方法。

代码写入并保存成功:

File path  = new File(this.getFilesDir().getPath());
            String value = "vegetables";
            // File output = new File(path + File.separator + fileName);
            File output = new File(getApplicationContext().getExternalFilesDir(null),"shopping.txt");
            try {
                FileOutputStream fileout = new FileOutputStream(output.getAbsolutePath());
                OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
                outputWriter.write(value);
                outputWriter.close();
                //display file saved message
               // Toast.makeText(getBaseContext(), "File saved successfully!",
                 //       Toast.LENGTH_LONG).show();
                Toast.makeText(MainActivity.this,String.valueOf(output),Toast.LENGTH_LONG).show();
                Log.d("MainActivity", "Chemin fichier = [" + output + "]");
            }
            catch (IOException e) {
                Log.e("Exception", "File write failed: " + e.toString());
            }
        }

编写代码使我的应用程序崩溃:

try
            {
                File gFile;
                FileInputStream fis = new FileInputStream (new File("shopping.txt"));
                //FileInputStream fis = openFileInput("/storage/emulated/0/Android/data/com.example.namour.shoppinglist/files/shopping.txt");
                BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
                String line = null, input="";
                while ((line = reader.readLine()) != null)
                    input += line;

                Toast.makeText(MainActivity.this,line,Toast.LENGTH_LONG).show();
                reader.close();
                fis.close();
                Toast.makeText(MainActivity.this,"Read successful",Toast.LENGTH_LONG).show();
                //return input;
            }
            catch (IOException e)

            {
                Log.e("Exception", "File read failed: " + e.toString());
                //toast("Error loading file: " + ex.getLocalizedMessage());

            }

我做错了什么? 当然,不是权限问题,因为我可以写成功。

非常感谢您的帮助。

【问题讨论】:

  • 这是一个FileNotFoundException,这意味着你正在检查的文件的路径是错误的。
  • 在第二段代码中,您没有指定任何父目录。

标签: java android


【解决方案1】:

您没有指定正确的路径。您正在当前工作目录(运行时)中查找名为 shopping.txt 的文件。 创建一个具有正确路径的新文件对象,它将起作用:
File input = new File(getApplicationContext().getExternalFilesDir(null),"shopping.txt");。你可以在写作中重用你的对象。

【讨论】:

  • 不错!你是对的,我在写入方法上对齐了我的读取方法,包括你建议的这个文件对象,它工作正常。非常感谢ItFreak
【解决方案2】:

打开文件时,您只是在使用new File("shopping.txt")。 您需要指定父文件夹,如下所示:

new File(getExternalFilesDir(),"shopping.txt");

【讨论】:

  • 对,请看上面我对代码中文件上下文的评论,感谢您的建议。
【解决方案3】:

我建议您确保为 IO 使用 org.apache.commons.io,它们的 FileUtilsFileNameUtils 库非常棒。即:FileUtils.writeStringToFile(new File(path), data); 如果您想使用它,请将其添加到 gradle:implementation 'org.apache.commons:commons-collections4:4.1'

关于您的问题。当您编写您正在使用的文件时:

getApplicationContext().getExternalFilesDir(null),"shopping.txt"

但是在阅读您正在使用的文件时:

FileInputStream fis = new FileInputStream (new File("shopping.txt"));

请注意,您没有指定shopping.txt 的路径,只是指定了文件名。

为什么不这样做呢:

//Get path to directory of your choice 
public String GetStorageDirectoryPath()
{
    String envPath = Environment.getExternalStorageDirectory().toString();
    String path = FilenameUtils.concat(envPath, "WhateverDirYouWish");
    return path;
}

//Concat filename with path
public String GetFilenameFullPath(String fileName){
    return FilenameUtils.concat(GetStorageDirectoryPath(), fileName);
}

//Write
String fullFilePath = GetFilenameFullPath("shopping.txt");
FileUtils.writeStringToFile(new File(fullFilePath ), data);

//Read
File file = new File(fullFilePath);
StringBuilder text = new StringBuilder();

BufferedReader br = new BufferedReader(new FileReader(file));
String line;

while ((line = br.readLine()) != null){
      text.append(line);
    if(newLine)
      text.append(System.getProperty("line.separator"));
}
br.close();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 2013-12-22
    • 2019-06-08
    相关资源
    最近更新 更多