2013-11-20 52 views
1

我試圖用掃描儀類讀取.java文件,但顯然不起作用。試圖讀取與掃描儀類的.java文件

File file = new File("program.java"); 
Scanner scanner = new Scanner(file); 

我只是想輸出program.java的代碼。 任何想法?假定所有文件都包含在一個文件夾中。因此沒有必要的途徑。

+1

發生了什麼事?你有錯誤嗎?該文件是否在正確的位置? –

+0

它輸出文件名。但是我想輸出program.java的代碼 – Mark

+0

爲什麼你在「program.java」周圍有雙括號?你只需要一套,不認爲這會解決你的問題。 – turbo

回答

2
try { 
     File file = new File("program.java"); 
     Scanner scanner = new Scanner(file); 
     while(scanner.hasNextLine()) 
     System.out.println(scanner.nextLine()); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 

你已經得到它的權利,直到掃描對象的創建。現在您只需檢查掃描儀是否有更多線路。如果是,請獲取下一行並打印。

0

要從java文件中讀取內容,您必須使用FileInputStream
請參閱以下代碼:

File file = new File(("program.java")); 
FileInputStream fis = null; 

try { 
     fis = new FileInputStream(file); 
     int content; 
     while ((content = fis.read()) != -1) { 
     System.out.print((char) content); 
     } 
     } catch (IOException e) { 
     e.printStackTrace(); 
     } finally { 
     try { 
      if (fis != null) 
       fis.close(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 

請檢查。

+0

Downvoter你可以請給我一個評論,以便我可以提高我的答案。 –

0

可以使用BufferedReader對象在文本文件中讀取:

try { 

    BufferedReader file = new BufferedReader(new FileReader("program.java")); 
    String line; 
    String input = ""; // will be equal to the text content of the file 

    while ((line = file.readLine()) != null) 
     input += line + '\n'; 

    System.out.print(input); // print out the content of the file to the console 

} catch (Exception e) {System.out.print("Problem reading the file.");} 



其他景點:

你必須讀入文件時要使用的try-catch

您可以取代Exception(它會趕上在運行時在代碼中的任何錯誤)來完成:
IOException(只趕上輸入輸出除外)或
FileNotFoundException(將捕獲的錯誤,如果文件未找到)。

或者你可以將它們結合起來,例如:

} 
catch(FileNotFoundException e) 
{ 
    System.out.print("File not found."); 
} 
catch(IOException f) 
{ 
    System.out.print("Different input-output exception."); 
} 
catch(Exception g) 
{ 
    System.out.print("A totally different problem!"); 
}