Reputation: 2023
In Java how can I take the data of my file on my display screen? I want to use data in my file and also want that data to be displayed on my output screen when I execute my program. Can any body please help by providing me such example in Java language. Thank you!
Upvotes: 1
Views: 659
Reputation: 199225
A modified version of this example:
import java.io.*;
class Demo {
public static void main( String [] args ) {
try {
BufferedReader in = new BufferedReader(new FileReader("youFile.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println( str );
}
in.close();
} catch (IOException e) {}
}
}
This is not precisely a "best practice" demo ( ie You should not ignore exceptions) , just what you needed: take data from file and display it on the screen"
I hope you find it helpful.
Upvotes: 1
Reputation: 383746
This is an "I/O" topic (input/output). The related classes are in package java.io
.
If you're reading a simple text file, java.util.Scanner
can be very useful. There are many examples in the documentation, and also elsewhere on StackOverflow.
The following code takes a filename from the command line, treating it as a text file, and simply print its content to standard output.
import java.util.*;
import java.io.*;
public class FileReadSample {
public static void main(String[] args) throws FileNotFoundException {
String filename = args[0]; // or use e.g. "myFile.txt"
Scanner sc = new Scanner(new File(filename));
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
}
}
You can compile this, and then run it as, say, java FileReadSample myFile.txt
.
For beginners, Scanner
is recommended, since it doesn't require complicated handling of IOException
.
Scanner.hasNextLine()
true
if there is another line in the input of this scanner.Scanner.nextLine()
Scanner.ioException()
IOException
last thrown by this Scanner
's underlying Readable
. This method returns null
if no such exception exists.Upvotes: 2
Reputation: 120
// Create
Path file = ...;
try {
file.createFile(); //Create the empty file with default permissions, etc.
} catch (FileAlreadyExists x) {
System.err.format("file named %s already exists%n", file);
} catch (IOException x) {
//Some other sort of failure, such as permissions.
System.err.format("createFile error: %s%n", x);
}
// Read
Path file = ...;
InputStream in = null;
try {
in = file.newInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException x) {
System.err.println(x);
} finally {
if (in != null) in.close();
}
Upvotes: 1