我可以使用VS代码在JAVA中使用.txt文件吗?

问题描述 投票:0回答:2

enter image description here

我正在尝试访问java中的文本文件和我在其他IDE中工作的代码,但在VS代码中它一直说

File Not Found
-(由我的异常处理产生)

我找不到任何有关如何使用 VScode 访问文本文件的信息。请问这可能吗?有人知道怎么做吗?

我尝试使用

new text file
选项在 VScode 中创建文件,并且还加载预先存在的文件,每次都得到相同的结果

java visual-studio-code text-files
2个回答
0
投票

.txt
文件放在项目根目录中,以便代码读取到该文件位置。如下图

enter image description here

如果该文件不在项目中,请在代码中使用绝对路径。

enter image description here


0
投票

tldr;某些字符会引起问题。

我以为我要疯了,直到我用下面的调试代码检查了所有可能性。当您确定文件存在、不存在权限问题、文件名正确并且 VsCode 正在运行并访问同一位置的文件等(下面的调试代码将检查这一点)时,则可能存在有问题的字符.

这里有一些可能有用的调试代码:


    System.out.println("Working Directory = " + System.getProperty("user.dir"));
        // Use the absolute path to ensure correctness
        File myFile = new File("C:\\Users\\PATH\\TO\\filename.txt");
        //File myFile = new File("filename.txt"); // also works with non-absolute like this
        System.out.println(myFile.getAbsolutePath());

        // Print the absolute path to ensure it's the correct file
        System.out.println("Absolute Path: " + myFile.getAbsolutePath());

        // Check if the file exists
        if (myFile.exists()) {
            System.out.println("File Exists");

            // Check if the file is readable
            if (myFile.canRead()) {
                System.out.println("File is readable");

                // Check if the file is a regular file (not a directory)
                if (myFile.isFile()) {
                    System.out.println("File is a regular file");

                    try (Scanner myScanner = new Scanner(myFile)) {
                        // Check if there are lines to read
                        System.out.println("Has next line: " + myScanner.hasNextLine());

                        while (myScanner.hasNextLine()) {
                            String line = myScanner.nextLine();
                            System.out.println(line);
                        }
                    } catch (FileNotFoundException e) {
                        System.out.println("Error opening file: " + e.getMessage());
                    }
                } else {
                    System.out.println("Path is not a regular file");
                }
            } else {
                System.out.println("File is not readable");
            }
        } else {
            System.out.println("File does not exist: " + myFile.getAbsolutePath());
        }

我正在中国用一台计算机解决这个问题,其中汉字有时不匹配。对于那些更高的值,VsCode 的 unicode 似乎被搞砸了。例如我有一个包含以下几行的文件:

line

newline 何热

合理

你好

VsCode 将其打印为:

line

newline 浣曠儹

鍚堢悊

浣犲ソ

我注意到,如果我的文件结尾,这个字符“啊”(可能还有其他字符)就会有麻烦。特别是 hasNextLine() 返回 false。但我可以再加一个字,比如改成“啊跑”,就没有问题了。也许有人可以找出映射问题是什么并将其提交给 VsCode 开发人员。我只能想象在与 Scanner 对象交互时某些无效的 unicode 或某些东西导致了问题。由于这完全是一个单独的问题/只是我的猜测,所以我现在不会断言任何具体内容。

© www.soinside.com 2019 - 2024. All rights reserved.