首页 > 解决方案 > 无法在 Android Studio (Java) 上查找和读取文本文件

问题描述

所以我正在使用 Android Studio 创建一个移动应用程序,它允许用户随机化并生成一个字符。我正在尝试逐行读取字符名称的 .txt 文件,以便我可以填充一个包含所有名称的 ArrayList。我试图读取 .txt 文件的一切尝试都没有奏效,控制台总是声称该目录和文件不存在。我尝试过以多种方式使用 BufferedReader、InputStreamReader 和 Scanner,如下所示:


ArrayList<String> a = new ArrayList<>();

try {

            File file = new File(fileName);

            InputStream in = new FileInputStream(file);

            BufferedReader br = new BufferedReader(new InputStreamReader(in));

            String curLine = br.readLine();
            while (curLine != null){
                a.add(curLine);
                curLine = br.readLine();
            }

        }
        catch (Exception e){

        }

和...


ArrayList<String> a = new ArrayList<>();

try (
            BufferedReader reader = new BufferedReader(new FileReader(fileName));
                ){
            String curLine = reader.readLine();
            for (int i = 1; i != lineNum; i++){
                a.add(curLine);
                curLine = reader.readLine();
            }
            return curLine;
            }
            
        
        catch (Exception e){
           
        }

和...


ArrayList<String> a = new ArrayList<>();

try {
            File myObj = new File(fileName);
            System.out.println(myObj.getAbsolutePath());
            Scanner myReader = new Scanner(myObj);
            while (myReader.hasNextLine()) {
                a.add(myReader.nextLine());
            }
            myReader.close();
        } catch (Exception e) {

        }

尽管它们都无法正常工作。我尝试使用 file.getAbsolutePath() 显示绝对路径并且路径是正确的。我尝试将文件与 src 文件夹平行放置在与 src 文件夹平行的文件夹中,在 res 文件夹中等等。此外,可能需要注意的是,我通过调用 FileIO 类中的静态方法来运行这些行,在该类中我将字符串文件名作为参数传递。有什么我想念的吗?当我在 NetBeans 或 Eclipse 中执行此操作时,我从文本文件中读取没有问题,事实上,当我在 Android Studio 中尝试此操作时,我在 NetBeans 中的一些旧项目已成为我的模板。

这是我第一个使用 Android Studio 的项目,所以我很可能做错了什么,所以任何帮助都将不胜感激!

注意:我知道我在提供的代码中捕获异常的约定效率不高,但是当我尝试使用 FileNotFoundException 捕获异常时,Android Studio 中的调试器由于某些奇怪的原因无法工作。

标签: javaandroidtextbufferedreaderfileinputstream

解决方案


你可以试试这个:

ArrayList<String> a = new ArrayList<>();
File file = new File(filename);

StringBuilder text = new StringBuilder();

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

        while ((line = br.readLine()) != null) {
            a.add(myReader.nextLine());
         }
        br.close();
    }
    catch (IOException e) { // OR CATCH AT LEAST EXCEPTION IF IT DOESNT WORK FOR FILEIOEXCEPTION
     // HERE LOG YOUR ERROR AND GIVE IT TO US
    }

确保您的“文件名”不是目录。通过记录一些断言的结果来测试你的文件:

System.out.println("file exists? " + file.exists());
System.out.println("file is Dir? " + file.isDirectory());
System.out.println("file can be read? " + file.canRead());

并给我们结果。


推荐阅读