简体   繁体   中英

Trying to read a .java file with a scanner class

I'm trying to read a .java file with a scanner class, but that obviously doesn't work.

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

I'm just trying to output the code of program.java. Any ideas? Assume that all the files are contained in one folder. Therefore there is no pathway needed.

  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();
    }

You have got it right till the scanner object creation. Now all you have to do is check the scanner if it has more lines. If it does, get the next line and print it.

To read the content from a file in java you have to use FileInputStream .
Please see the below code:

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();
        }
    }

Please check.

You can use the BufferedReader object to read in your text file:

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.");}



Additional points:

You have to use the try-catch when reading in a file.

You could replace Exception (it will catch any error made in your code during run-time) to either:
IOException (will only catch an input-output exception) or
FileNotFoundException (will catch the error if the file is not found).

Or you could combine them, for example:

}
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!");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM