I'm attempting to learn more about Java and have created a method that takes a text file with stdout
(space separated file) and converts it to a CSV file.
I was attempting to use standard Java SE version 8.
Is there a better, more efficient, way of doing this?
The logic is:
- Open file
- Read file by line into string so it can be split
- Split string removing spaces, back into array
- Join with
StringJoiner
using,
- Convert back to string to remove leading
,
- Update final array to be returned
Method to open file:
public void OpenFile(String fileName)
{
try
{
subFile = new Scanner (new File(fileName));
}
catch (Exception e)
{
System.out.println("File dosn't exist.");
}
}
Method to convert:
public String[] TextToCsvArray(String[] fileArray)
{
int i=0;
while(subFile.hasNext())
{
String line = subFile.nextLine();
String[] split = line.split("\\s+");
StringJoiner joiner = new StringJoiner(",");
for (String strVal: split)
joiner.add(strVal);
line = joiner.toString();
line = line.startsWith(",") ? line.substring(1) : line;
fileArray[i++] = line;
}
return fileArray;
}