So given an input file, input.txt. I am trying to write a program that will firstly: print each line from input.txt line by line as it appears in the text file. So lets say the text file says:
This line first
This line seccond
Then when I print it should say:
This line first
This line seccond
Secondly, I want to print such that the input text reads:
This
line
first
This
line
seccond
Thirdly, I want to write to a file such that the output matches the input. So again if the input is:
This line first
This line seccond
Then the output file (outputTextA in this case) should read:
This line first
This line seccond
Here is my code for doing those first three steps and it works just fine:
String inputFile = "src/input/input.txt"; String outputFileA = "src/output/outputA.txt"; String outputFileB = "src/output/outputB.txt"; StringBuilder outputStringA = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))){ String line; while ((line = reader.readLine()) != null){ outputStringA.append(line); if (line != null){ outputStringA.append(System.lineSeparator()); } } System.out.println(outputStringA); }catch(IOException x){ System.err.format("IOException: %s%n", x); } String s1 = outputStringA.toString(); for (String word : s1.split(" ")){ System.out.println(word); } try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileA))){ writer.write(s1, 0, outputStringA.length()); }catch(IOException x){ System.err.format("IOException: %s%n", x); }
Now, I want to output to a file such that if the input text is:
This line first
This line seccond
Then the output text would be:
This
line
first
This
line
seccond
However, I cannot figure out how!
I have tried many things none of which are working. I have tried:
for (String word : s1.split(" ")) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileB))) { writer.write(word, 0, outputStringA.length()); } catch (IOException x) { System.err.format("IOException: %s%n", x); } }
However this throws and exception. I have also tried:
try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileA))) { for (String word : s1.split(" ")) { writer.write(word, 0, outputStringA.length()); } } catch (IOException x) { System.err.format("IOException: %s%n", x); }
However, this also throws and exception.
There must be an easier way can someone please help me out?
--- Update ---
Just a quick note I also tried converting the string s1 into an array list. Then tried writting the array list to the file like this:
List<String> myList = new ArrayList<String>(Arrays.asList(s1.split(" ")));
Then although I was able to write the list into the file I could not figure out how to write the list into the file in the proper format.