无法在Android Studio(Java)中找到并读取文本文件。

huangapple 未分类评论45阅读模式
英文:

Cannot Find and Read Text File on Android Studio (Java)

问题

所以我正在使用Android Studio创建一个移动应用程序,允许用户随机生成角色。我试图逐行读取包含角色姓名的.txt文件,以便能够填充一个ArrayList<String>以保存所有姓名。我尝试过多种方法来读取.txt文件,但始终无法成功,控制台始终声称目录和文件不存在。我尝试过使用BufferedReader、InputStreamReader和Scanner,如下所示:

ArrayList&lt;String&gt; a = new ArrayList&lt;&gt;();

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&lt;String&gt; a = new ArrayList&lt;&gt;();

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&lt;String&gt; a = new ArrayList&lt;&gt;();

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类中的静态方法来运行这些代码,其中我将String fileName作为参数传递进去。我是否漏掉了什么?当我在NetBeans或Eclipse中执行此操作时,从文本文件中读取没有问题,实际上,NetBeans中的一些旧项目已经成为我在Android Studio尝试时的模板。

这是我在Android Studio中的第一个项目,所以我很可能做错了一些事情,所以非常感谢任何帮助!

注:我知道我在提供的代码中捕获异常的方式不高效,但当我尝试使用FileNotFoundException捕获异常时,Android Studio中的调试器因某种奇怪的原因无法正常工作。

英文:

So I am creating a mobile application using Android Studio that allows the user to randomize and generate a character. I am trying to read a .txt file of the characters' names, line by line, so that I can populate an ArrayList<String> that will hold all the names. Everything I have tried in an attempt to read the .txt file has not worked and the console always claims that the directory and file doesn't exist. I have tried using a BufferedReader, InputStreamReader, and Scanner in many ways, as shown below:


ArrayList&lt;String&gt; a = new ArrayList&lt;&gt;();

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){

        }

and...


ArrayList&lt;String&gt; a = new ArrayList&lt;&gt;();

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){
           
        }

and...


ArrayList&lt;String&gt; a = new ArrayList&lt;&gt;();

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) {

        }

though all of them fail to work. I have tried showing the absolute path using file.getAbsolutePath() and the path is correct. I have tried putting the file parallel to the src folder, in a folder that is parallel with the src folder, in the res folder, and more. In addition, it may be important to note that I am running these lines by calling a static method in my FileIO class where I am passing in the String fileName as an argument. Is there something I'm missing? When I do this in NetBeans or Eclipse I have no issue with reading from a text file, in fact some of my old projects in NetBeans have been a template for me when I'm attempting this in Android Studio.

This is my first project with Android Studio so I am most likely doing something incorrect, so any help would be appreciated!

Note: I know that my convention for catching Exceptions is not efficient in the code provided, though when I try to catch the Exception with a FileNotFoundException, the debugger in Android Studio fails to work for some odd reason.

答案1

得分: 0

请尝试以下代码

    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(line);
        }
        br.close();
    } catch (IOException e) {
        // 在此记录错误并提供给我们
    }

确保你的filename不是一个目录
通过记录一些断言的结果来测试你的文件

    System.out.println("文件是否存在?" + file.exists());
    System.out.println("文件是目录?" + file.isDirectory());
    System.out.println("文件可读?" + file.canRead());

并将结果反馈给我们
英文:

Can you try this :

ArrayList&lt;String&gt; a = new ArrayList&lt;&gt;();
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
    }

Ensure that your "filename" is not a directory.
Test your file by logging results of some assertions:

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

and give us the results.

huangapple
  • 本文由 发表于 2020年7月26日 06:11:38
  • 转载请务必保留本文链接:https://java.coder-hub.com/63094070.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定