当我尝试读取文件时为什么会出现NullPointerException?

7

我使用这个测试将txt格式转换为pdf格式:

package convert.pdf;

//getResourceAsStream(String name) : Returns an input stream for reading the specified resource.
//toByteArray : Get the contents of an InputStream as a byte[].

import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.io.IOUtils;

import convert.pdf.txt.TextConversion;

public class TestConversion {

  private static byte[] readFilesInBytes(String file) throws IOException {
      return IOUtils.toByteArray(TestConversion.class.getResourceAsStream(file));
  }

  private static void writeFilesInBytes(byte[] file, String name) throws IOException {
      IOUtils.write(file, new FileOutputStream(name));
  }

  //just change the extensions and test conversions
  public static void main(String args[]) throws IOException {
      ConversionToPDF algorithm = new TextConversion();
      byte[] file = readFilesInBytes("/convert/pdf/text.txt");
      byte[] pdf = algorithm.convertDocument(file);
      writeFilesInBytes(pdf, "text.pdf");
  }

}

问题:

在主线程中发生异常 java.lang.NullPointerException
    at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1025)
    at org.apache.commons.io.IOUtils.copy(IOUtils.java:999)
    at org.apache.commons.io.IOUtils.toByteArray(IOUtils.java:218)
    at convert.pdf.TestConversion.readFilesInBytes(TestConversion.java:17)
    at convert.pdf.TestConversion.main(TestConversion.java:28)

我使用了调试器,问题似乎出现在这里:

  private static byte[] readFilesInBytes(String file) throws IOException {
      return IOUtils.toByteArray(TestConversion.class.getResourceAsStream(file));
  }

我的问题是什么?
4个回答

20

听起来这个资源可能不存在这个名称。

你是否知道Class.getResourceAsStream()会相对于该类的包查找资源,而ClassLoader.getResourceAsStream()则不会?在Class.getResourceAsStream()中使用前导斜杠可以模仿这一点,所以

Foo.class.getResourceAsStream("/bar.png")

大致等同于

Foo.class.getClassLoader().getResourceAsStream("bar.png")

您实际上是在加载一个文件(即普通文件系统中的特定文件)吗?如果是,使用FileInputStream会更好。如果是封装在jar文件或类路径中的资源,请使用Class.getResourceAsStream();如果它是任意可能存在于文件系统中任何位置的文件,请使用FileInputStream

编辑:还有一件需要注意的事情,之前曾让我遇到过问题-如果在开发环境中(假设为Windows)工作正常,但在生产服务器上(假设为Unix)失败了,请检查文件名的大小写。不同的文件系统对大小写敏感性的处理方式可能会带来麻烦...


1
你是否在将文件传递给readFilesInBytes()之前检查它是否存在?请注意,如果找不到文件,Class.getResourceAsStream()会返回null。你可能想要这样做:
private static byte[] readFilesInBytes(String file) throws IOException {
  File testFile = new File(file);
  if (!testFile.exists()) {
      throw new FileNotFoundException("File " + file + " does not exist");
  }
  return IOUtils.toByteArray(TestConversion.class.getResourceAsStream(file));
}

或者更好的是:

private static byte[] readFilesInBytes(String file) throws IOException {
  InputStream stream = TestConversion.class.getResourceAsStream(file);
  if (stream == null) {
      throw new FileNotFoundException("readFilesInBytes: File " + file
                                      + " does not exist");
  }
  return IOUtils.toByteArray(stream);
}

0

这个问题可能是由于在test.txt上调用方法引起的,它可能是一个文件夹快捷方式。换句话说,您正在调用一个不存在的文件的方法,导致了NullPointerException


0
这个类在类路径中读取一个TXT文件,并使用TextConversion将其转换为PDF,然后将PDF保存在文件系统中。
这里是TextConversion代码:
package convert.pdf.txt;
//Conversion to PDF from text using iText.
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import convert.pdf.ConversionToPDF;
import convert.pdf.ConvertDocumentException;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

public class TextConversion implements ConversionToPDF {

    public byte[] convertDocument(byte[] documents) throws ConvertDocumentException {
        try {
            return this.convertInternal(documents);
        } catch (DocumentException e) {
            throw new ConvertDocumentException(e);
        } catch (IOException e) {
            throw new ConvertDocumentException(e);
        }
    }

    private byte[] convertInternal(byte[] documents) throws DocumentException, IOException {
        Document document = new Document();

        ByteArrayOutputStream pdfResultBytes = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, pdfResultBytes);

        document.open();

        BufferedReader reader = new BufferedReader( new InputStreamReader( new ByteArrayInputStream(documents) ) );

        String line = "";
        while ((line = reader.readLine()) != null) {
            if ("".equals(line.trim())) {
                line = "\n"; //white line
            }
            Font fonteDefault = new Font(Font.COURIER, 10);
            Paragraph paragraph = new Paragraph(line, fonteDefault);
            document.add(paragraph);
        }

        reader.close();

        document.close();

        return pdfResultBytes.toByteArray();
    }
}

这里是将代码转换为PDF的代码:

package convert.pdf;
// Interface implemented by the conversion algorithms.
public interface ConversionToPDF {

    public byte[] convertDocument(byte[] documentToConvert) throws ConvertDocumentException;
    }

我认为问题出在我的文件系统上(devbox在Windows上,服务器是Unix)。 我将尝试修改我的类路径。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接