【问题标题】:create and write files , return boolean创建和写入文件,返回布尔值
【发布时间】:2018-03-18 03:25:03
【问题描述】:

编写一个名为 q1 的公共静态方法,该方法不带参数,返回类型为布尔值。此方法将尝试打开名为“location.txt”的文件,如果文件存在并且在任何行包含字符串“statistical”作为子字符串,则返回 true,如果未找到“statistical”则返回 false。如果 "location.txt" 不存在,此方法也会返回 false。

这就是我所做的,我不知道如何将其作为布尔值。

public static boolean q1() {

    String filename = x;
// creating file name location.txt   
 try {
     String x = "location.txt";
     System.out.print("location.txt file has been created");
     String textToWrite = "statistical";
     Files.write(Paths.get(x), textToWrite.getBytes());
 }
catch (IOException e) {
    boolean r = false;
    return r;
}
 BufferedReader br = new BufferedReader(new FileReader("location.txt"));
 String textToWrite;
 while ((textToWrite = br.readLine()) != null) {

 }

 return f;

}

【问题讨论】:

  • 作业说你必须读取文件,那你为什么要写入呢?另外至少尝试打印异常,否则您不知道发生了什么。

标签: java


【解决方案1】:

使用 Java 8 中引入的 Stream API:

/**
 * Returns whether the file 'location.txt' exists and any line contains the string "statistical".
 *
 * @return true if the file exists and any line contains "statistical", false otherwise
 * @throws IOException if an I/O error occurs
 */
public static boolean q1() throws IOException {
    Path path = Paths.get("location.txt");
    try (Stream<String> lines = Files.lines(path)) {
        return lines.anyMatch(line -> line.contains("statistical"));
    } catch (FileNotFoundException e) {
        return false;
    } catch (UncheckedIOException e) {
        // Stream wraps IOExceptions, because streams don't throw checked exceptions. Unwrap them.
        throw e.getCause();
    }
}

编辑:使用 try-with-resource 来处理文件系统资源。

返回的流封装了一个 Reader。如果需要及时处理文件系统资源,则应使用 try-with-resources 构造来确保在流操作完成后调用流的 close 方法。

编辑 2:解开流的 UncheckedIOException 以使调用者更容易处理异常。

在此方法返回后,从文件读取或读取格式错误或不可映射的字节序列时发生的任何后续 I/O 异常都将包装在 UncheckedIOException 中,该异常将从导致读取的 Stream 方法中抛出发生。如果关闭文件时抛出 IOException,它也会被包装为 UncheckedIOException。

【讨论】:

    【解决方案2】:

    您的代码的第一部分似乎是创建一个满足给定标准的文件(也就是说,它使以下代码变得毫无意义)。不要那样做。逐行读取文件。检查您阅读的行是否包含您正在搜索的字符串。如果是return true。否则return false。喜欢,

    public static boolean q1() {
        String fileName = "location.txt", toFind = "statistical";
        try (BufferedReader br = new BufferedReader(new FileReader(new File(fileName)))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.contains(toFind)) {
                    return true;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
    

    【讨论】:

    • 投反对票的人能否解释一下这个答案有什么问题?它具有编写良好的代码;清晰合理的解释;并正确解决了原来的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多