reading text file and assigning strings from file to variables
bufferedreader, filereader, java
Solution
You have to read one line with `readLine()` then you say that you want to split with `whitespace`.
So you have to do something like this
String line=null;
List<Course> courses = new ArrayList<>();
while ((line = inputFile.readLine())!= null) {
String[] arrayLine= line.split("\\s+"); // here you are splitting with whitespace
courseName = arrayLine[0]
lName=arrayLine[1];
officeNumber=arrayLine[2];
list.add(new Course(courseName,lName,officeNumber));
// you sure want do something with this create an object for example
}
// in some part br.close();
Here you have an example How to read a File
Problem
I have a few problems with my code. I want to be able to read input from a text file and take the strings from each line or between spaces and assign them to variables that I will pass to an object. My first problem is that my program misreads one of my lines and omits the first letter from a variable, and the second problem is I don't know how to make my program read two strings on the same line and assign them to different variables. ``` System.out.println("Input the file name of the text file you want to open:(remember .txt)"); keyboard.nextLine(); String filename=keyboard.nextLine(); FileReader freader=new FileReader(filename); BufferedReader inputFile=new BufferedReader(freader); courseName=inputFile.readLine(); while (inputFile.read()!= -1) { fName=inputFile.readLine(); lName=inputFile.readLine(); officeNumber=inputFile.readLine(); } System.out.println(fName); Instructor inst=new Instructor(fName,lName,officeNumber); System.out.println(inst); inputFile.close(); } ``` I am not very good at using filereader and have tried to use the scanner keyboard method, but it lead me to even more errors :( Output: Input from a file (F) or keyboard (K): F Input the file name of the text file you want to open: (remember .txt) test.txt un bun un bun won won's office number is null text file: professor messor bun bun won won