Java有时在读取文件时返回空字符串

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

这很奇怪,但我不知道为什么会导致它。

我正在使用Java 10并试图读取文件。有时读取文件并将文件内容输出到控制台,但是有时它根本不输出内容。

我已经确认它可以读写文件,并且在我使用的字符串变量中包含某些内容,但是无论返回什么内容,它有时都会阻止任何内容打印到控制台。

有时它会在前几次工作,然后在接下来的十次失败。所有其他代码均按预期工作,除非它与此隐藏变量进行交互。没有异常被抛出。

这里是要测试的代码。

public String getText(String filePath) {
        File file = new File(filePath);
        System.out.println(file.getAbsolutePath());
        System.out.println(file.exists());
        System.out.println(file.canRead());

        String text = null;
        System.out.println("try getting file content");

        try {
            byte[] array =Files.readAllBytes(file.toPath());
            System.out.println(""+array.length);
            text = new String(array,  StandardCharsets.UTF_8);
        }catch(Exception e) {
            System.out.println(e.getMessage());
        }
        if(text != null) {
            System.out.println("file content have been retrieved successfully");
            System.out.println("["+text+"]"); //this line won't print sometimes
        }

        return text;
    }
java file java-10
1个回答
0
投票

如果文本不在UTF-8中,则转换为UTF-8可能会导致错误,因为它可能会遇到错误的“多字节序列。”

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