How to Take Input From a File in Java
- 1). Right-click the Java file you want to edit and select "Open With." Click the Java editor you want to use to edit the code.
- 2). Add the following code at the top of the Java file to include the IO library:
import java.io.*; - 3). Open the file using the following code:
File file = new File("C:\myfile.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
Replace the text file in the sample with your own file. The code above opens the file and then creates a handler, so you can loop through and read the file's content. - 4). Read a line of input from the file. You can loop through the input or read only one line. The following code reads the first line and stores the input in the "var" variable:
string var;
var = reader.readLine()
Source...