Search code examples
javaarraysjtextarea

Split array from txt file and append \n. Display each entry on single line in TextArea


I want to open a .txt file, split the contents by the character ` and then display the contents of this array, each entry on a single line to the user.

I have achieved similar with android so my code below is based on that:

try {
        // open the file
        File myFile = new File(f + "mx.txt");
        FileInputStream fIn = new FileInputStream(myFile);
        BufferedReader myReader = new BufferedReader(new InputStreamReader(
                fIn));
        String aDataRow = "";
        String aBuffer = "";
        while ((aDataRow = myReader.readLine()) != null) {
            aBuffer += aDataRow + "\n";
        }

        // String loadeddata = aBuffer;
        String[] splitdata = aBuffer.split("`"); // recover the file and
                                                    // split it based on `

        myReader.close();

        System.out.println(Arrays.toString(splitdata));
        txtDataWillBe.setText(Arrays.toString(splitdata));

    } catch (Exception ez) {
        System.out.println("error in array building");
    }

The array loads fine but displays in the text area as a single line.

My question is, how to I split the array and add a '\n', or is there another way to display the array one entry per line?

Also, can I prevent the textarea from expanding beyond the window that is open and display vertical scroll bars if required?

Thanks for any help. Andy


Solution

  • You can loop over String[] splitdata and combine each String using System.getProperty("line.separator");

    String lines = "";
    for(String line : splitdata){
    lines = lines + line + System.getProperty("line.separator");
    }