This is so aggravating after having spent so much time to just get the output correct. Anyone have any tips here? I've played around with the trailing spaces and nothng works.
package com.codegym.task.task19.task1908;
/*
Picking out numbers
Read 2 file names from the console.
Output to the second file all of the numbers from the first file.
Separate the numbers with a space.
Close the streams.
Example file content:
12 text var2 14 8v 1
Result:
12 14 1
Requirements:
3. The program must read the first file's contents (use the BufferedReader constructor that takes a FileReader argument).
4. The file input stream (BufferedReader) must be closed.
5. The program must write all of the numbers from the first file, separated by spaces, to the second file (use the BufferedWriter constructor that takes a FileWriter argument).
6. The file output stream (BufferedWriter) must be closed.
*/
import java.io.*;
import java.util.ArrayList;
public class Solution {
public static void main(String[] args) throws IOException {
//1. The program should read file names from the console (use BufferedReader).
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileInputName = reader.readLine();
String fileOutputName = reader.readLine();
BufferedReader fileReader = new BufferedReader(new FileReader(fileInputName));
//2. The BufferedReader used for reading input from the console must be closed after use.
reader.close();
String line = null;
while(fileReader.ready()){
line = fileReader.readLine();
}
fileReader.close();
StringBuilder stringBuilder = new StringBuilder();
ArrayList<String> stringArrayList = new ArrayList<>();
for(int i = 0; i < line.length(); i++){
//if the current character is a digit and the next character isn't a space or a letter
//If current char is Digit...
if(Character.isDigit(line.charAt(i))){
//If next char is Digit, add it to your string.
if(i == line.length() - 1) {
stringBuilder.append(line.charAt(i));
stringArrayList.add(stringBuilder.toString());
break;
}else if(Character.isDigit(line.charAt(i + 1))){
stringBuilder.append(line.charAt(i));
//If next character is letter or previous character is letter, reset the string.
}else if(Character.isLetter(line.charAt(i + 1)) || Character.isLetter(line.charAt(i - 1))) {
stringBuilder = new StringBuilder();
//If next character is a space, add current character to string, add string to arraylist, and reset.
}else if (line.charAt(i + 1) == ' ') {
stringBuilder.append(line.charAt(i));
stringArrayList.add(stringBuilder.toString());
stringBuilder = new StringBuilder();
}
}else{
//Current character is not a digit.
stringBuilder = new StringBuilder();
}
}
BufferedWriter fileWriter = new BufferedWriter(new FileWriter((fileOutputName)));
for(int k = 0; k < stringArrayList.size(); k++){
if(k != stringArrayList.size() - 1){
fileWriter.write(stringArrayList.get(k) + " ");
}else{
fileWriter.write(stringArrayList.get(k) + "");
}
}
fileWriter.flush();
fileWriter.close();
}
}