2014-03-13 127 views
2

這是我使用itext創建pdf文檔的java代碼。Java編譯錯誤:忽略新實例

package com.cdac.pdfparser; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.util.*; 
import com.lowagie.text.Document; 
import com.lowagie.text.DocumentException; 
import com.lowagie.text.Paragraph; 
import com.lowagie.text.pdf.PdfWriter; 

public class PDFCreate { 
    public static String RESULT = "results/part1/chapter01/"; 
    public static void main(String[] args) 
    throws DocumentException, IOException { 
     Scanner sc = new Scanner(System.in); 
     String fileName = sc.nextLine(); 
     RESULT = RESULT + fileName; 
     new PDFCreate.createPdf(RESULT); 
    } 
    public void createPdf(String filename) 
    throws DocumentException, IOException { 
     // step 1 
     Document document = new Document(); 
     // step 2 
     PdfWriter.getInstance(document, new FileOutputStream(filename)); 
     // step 3 
     document.open(); 
     // step 4 
     document.add(new Paragraph("Hello World!")); 
     // step 5 
     document.close(); 
    } 
} 

但我發現了一個編譯錯誤:新實例忽略

請幫我...

回答

4
new PDFCreate.createPdf(RESULT); 
      -------^ 

這並不是創建一個Object的正確方法。

應該

new PDFCreate().createPdf(RESULT); 

你忘了寫()

+0

我也看到你重新分配的結果'RESULT = RESULT +文件名的值;'。字符串是不可改變的,這不是一個好習慣。 – anirudh

0

i change new PDFCreate.createPdf(RESULT) with new PDFCreate()。createPdf(RESULT);

PDFCreate.createPdf(RESULT)是不正確的方式來創建在java中的對象。

希望它的工作

package com.cdac.pdfparser; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.util.*; 
import com.lowagie.text.Document; 
import com.lowagie.text.DocumentException; 
import com.lowagie.text.Paragraph; 
import com.lowagie.text.pdf.PdfWriter; 




    public class PDFCreate { 
    public static String RESULT = "results/part1/chapter01/"; 
    public static void main(String[] args) 
    throws DocumentException, IOException { 
    Scanner sc = new Scanner(System.in); 
    String fileName = sc.nextLine(); 
    RESULT = RESULT + fileName; 
    new PDFCreate().createPdf(RESULT); 
    } 
    public void createPdf(String filename) 
    throws DocumentException, IOException { 
     // step 1 
     Document document = new Document(); 
     // step 2 
     PdfWriter.getInstance(document, new FileOutputStream(filename)); 
     // step 3 
     document.open(); 
     // step 4 
     document.add(new Paragraph("Hello World!")); 
     // step 5 
     document.close(); 

} }