My goal is to have a String that stores the contents of a file. I literally ripped the algorithm for reading a file from W3 schools (https://www.w3schools.com/java/java_files_read.asp) and simply changed a few things.
public class Fileparser {
public void fileParse(String filename) {
try {
File myObj = new File("C:\\Users\\(myname)\\Desktop\\" + filename);
Scanner myReader = new Scanner(myObj);
String output = "";
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
output.concat(data);
}
myReader.close();
System.out.println(output);
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
In main, of course, I have a Fileparser object that does the method with a file I have on my desktop, but it prints absolutely nothing. I had to wrestle with Java because I am unfamiliar with the scope of local variables. How come output prints nothing, when I am concatenating line by line to it?
String
javadoc states that: "String
s are constant; their values cannot be changed after they are created." Thus,output.concat(data);
returns a newString
, representing the concatenation. replace this line withoutput = output.concat(data);
.