D Hw1 Eatsleep n Ps2 controlF variablescha D controlPlowc T
D Hw1 Eatsleep.. n Ps2 controlF variablescha.... D controlPlowc... T PS1 variable. Functionsch.. Ps4 Datastru... FilesLecture... E3 \'13 1e import java.io.IOException; s1 test/src/PS1 Variables iava 2 import java.nio.file. Files; 3 import java.nio.file.Paths; 5 public class FilesLecture1 8 5 points 9e static string Q1 (string filename) 10 TODO: Read the input file and return its contents as a single string containing all lines of the file 11 Concatenated together. 12 try 13 filename \"src/test File txt 14 for (String line Files read ALL Lines (Paths.get (filename 15 System.out.println (line); 16 catch (IOException ex){ 18 ex.printstack Trace() 19 20 21 return 22 23 25e public static void main( String[] args) String result 01 src/test File.txt\") 26 system out.println(result); 27 28 no Javadoc Declaration E console 3 terminated FilesLecture1 Java Application] CAProgram FilesVava 121 binyavaw.exe (Feb 27, 2017, 9:41:44 AM You are reading this text from file!
Solution
What you need to do here is create a string and keep adding the output of file. To do this, you should use StringBuilder class which is optimal for it. So your code would look something like below
static String Q1(String fileName) {
StringBuilder builder = new StringBuilder();
try {
for (String line : Files.readAllLines(Paths.get(fileName))) {
builder.append(line);
}
}
catch (IOException ex) {
ex.printStackTrace();
}
return builder.toString();
}
