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