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
    org.apache.commons.io.IOUtils.copyLarge (IOUtils.java:1025) で
    org.apache.commons.io.IOUtils.copy (IOUtils.java:999) で
    org.apache.commons.io.IOUtils.toByteArray(IOUtils.java:218) で
    convert.pdf.TestConversion.readFilesInBytes(TestConversion.java:17) で
    convert.pdf.TestConversion.main(TestConversion.java:28) で

デバッガーを使用していますが、問題は次の場所にあるようです:

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

私の問題は何ですか?

4

4 に答える 4

20

その名前のリソースはおそらく存在しないようです。

Class.getResourceAsStream()はそのクラスのパッケージに関連するリソースを見つけますが、そうではありClassLoader.getResourceAsStream()ませんか? Class.getResourceAsStream()これを模倣するために先頭のスラッシュを使用できます。

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

とほぼ同等です

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

これは実際にロードしようとしているファイル (つまり、通常のファイル システム上の特定のファイル) ですか? もしそうなら、使用FileInputStreamする方が良いでしょう。Class.getResourceAsStream()jar ファイルまたは他の方法でクラスパスにバンドルされているリソースである場合に使用します。FileInputStreamファイルシステムのどこにでもある可能性のある任意のファイルである場合に使用します。

編集:注意すべきもう1つのことは、これまでに問題を引き起こしたものです-これがたまたまWindowsである開発ボックスで機能し、たまたまUnixである本番サーバーで失敗している場合は、ファイル名。異なるファイルシステムが大文字と小文字の区別を異なる方法で処理するという事実は、苦痛になる可能性があります...

于 2009-03-31T21:58:22.747 に答える
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);
}
于 2009-03-31T21:55:55.980 に答える
0

test.txtこの問題は、フォルダのショートカットである可能性があるのメソッドを呼び出すことによって発生する可能性があります。つまり、存在しないファイルでメソッドを呼び出しているため、結果は。になりNullPointerExceptionます。

于 2012-08-02T01:20:50.517 に答える
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();
    }
}

そしてここにConversionToPDFへのコード:

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

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

問題は私のファイルシステムにあると思います(WindowsとサーバーのdevboxはUnixです)。クラスパスを変更してみます。

于 2009-03-31T22:20:49.710 に答える