2016-05-10 178 views
-1

這裏有兩個Java類:如何使用FileInputStream從另一個類訪問輸入文件?

得到輸入文件:

public class Inputfile {  

public static void main(String[] args) throws Exception { 
    Scanner sc = new Scanner(System.in); 
    Scanner input = null; 
    boolean isFile = false; 
    while (isFile == false){ 
     System.out.print("Input file name? "); 
     String fileName = sc.next(); 

     File inputFile = new File(fileName); 
     if (inputFile.exists()){ 
      input = new Scanner(inputFile); 
      isFile = true; 
     }    
    } 

來解析輸入文件:

public class PdfParse { 

public static void main(final String[] args) throws Exception { 



Inputfile inputfile = new Inputfile(); 
String fileName; 
fileName = inputfile.toString();  
    FileInputStream inputstream = new FileInputStream(new File("fileName")); 


ParseContext pcontext = new ParseContext(); 
    ......... 
    } 

我得到的是FileNotfound異常的文件名。 我試圖使用字符串名稱,但我無法從輸入文件類使用getters獲取字符串名稱,但我失敗了。有人可以告訴我如何做到這一點?

謝謝了。

回答

2

您可以在Inputfile類定義getFileName方法

public class Inputfile {  

     public static String getFileName() throws Exception { 
     Scanner sc = new Scanner(System.in); 
     String fileName = null; 
     boolean isFile = false; 
     while (!isFile){ 
      System.out.print("Input file name? "); 
      fileName = sc.next(); 

      File inputFile = new File(fileName); 
      if (inputFile.exists()){ 
       isFile = true; 
      }    
     } 
     return fileName; 
    } 
} 

然後你可以使用上面的def在方法的mainPdfParse

public class PdfParse { 

     public static void main(final String[] args) throws Exception { 



     String fileName = InputFile.getFileName(); 

     FileInputStream inputstream = new FileInputStream(new File(fileName)); 


     ParseContext pcontext = new ParseContext(); 
     ......... 
     } 
    } 

希望這有助於獨立非執行董事方法。

+1

爲什麼我得到一個nullpointerexception當我使用此代碼? – smoothsipai

+0

你在哪裏得到'NullPointerException'? – Sanjeev

+0

明白了......現在就試試吧 – Sanjeev

1

您可以在文件傳遞給第二類:

Scanner sc = new Scanner(System.in); 
File inputFile = null; 
while (inputFile == null){ 
    System.out.print("Input file name? "); 
    String fileName = sc.next(); 

    inputFile = new File(fileName); 
    if (!inputFile.exists()){ 
     inputFile = null; 
    }    
} 

PdfParse.parse(input); // <-- Pass file to parser 

然後你PdfParse類看起來是這樣的:

public class PdfParse { 

    public static void parse(File inputFile) throws Exception { 
     FileInputStream inputstream = new FileInputStream(inputFile); 
     ... 
    } 

} 
+0

謝謝,Jorn!但其他答案更簡單。 :) – smoothsipai