0

我正在制作一个 slurp 方法,它本质上接受一个文件并将其内容作为字符串返回。

我不断收到异常错误,我不知道为什么。我不知道我是否抛出了错误的异常,但我需要帮助解决我收到异常的原因,因为我很难理解它们。错误追溯到该行

content = new String (Files.readAllBytes(Paths.get(file.getAbsolutePath())));

在 try { } 下方。

/**
   * Investigate Files.readAllBytes as a means of reading the file.
   * Reading files can fail if the file cannot be opened.
   * Mark this method as dangerous with a throws clause:
   * public static ...(...) throws IOException {
   * @return
   * @throws IOException
   */
  public static String slurp() throws IOException
  {
    String content = "";
    File file = new File(content);

    try
    {
      content = new String (Files.readAllBytes(Paths.get(file.getAbsolutePath())));
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }

    return content;
  }

错误说明了什么:

java.io.IOException: Is a directory
    at java.base/sun.nio.ch.FileDispatcherImpl.read0(Native Method)
    at java.base/sun.nio.ch.FileDispatcherImpl.read(FileDispatcherImpl.java:48)
    at java.base/sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:283)
    at java.base/sun.nio.ch.IOUtil.read(IOUtil.java:250)
    at java.base/sun.nio.ch.FileChannelImpl.read(FileChannelImpl.java:223)
    at java.base/sun.nio.ch.ChannelInputStream.read(ChannelInputStream.java:65)
    at java.base/sun.nio.ch.ChannelInputStream.read(ChannelInputStream.java:109)
    at java.base/sun.nio.ch.ChannelInputStream.read(ChannelInputStream.java:103)
    at java.base/java.nio.file.Files.read(Files.java:3163)
    at java.base/java.nio.file.Files.readAllBytes(Files.java:3216)
    at hw2.FileUtilities.slurp(FileUtilities.java:46)
    at hw2.FileUtilities.main(FileUtilities.java:14)
4

0 回答 0