Converting a text file to a CSV file 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;
}
If your input is already separated correctly by spaces, it seems all you need to do is to convert those into commas and you're good. I'm not sure you need to go to/from arrays.

I would replace the code inside the loop:

{
    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;            
}


with this:

{
    String line = subFile.nextLine();            
    line.trim().replaceAll(" +", " "); //check for double spaces
    line.replace(' ', ',');   //replace space with comma
    fileArray[i++] = line; 
}


Oh, and check for the array size like someone else mentioned.