2013-11-20 62 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!"); 
}