Search code examples
javaarraysstringfilewriterbufferedwriter

How to write or store string array in .txt file in java


I want to write string array in .txt file. But after running my code, I am getting an empty file. Here is my code.

public void DataSave() throws IOException {
        File fout = new File("Data.txt");
        FileOutputStream fos = new FileOutputStream(fout);

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

        String[] numberOfProperty = new String[3];
        numberOfProperty[0] = "1";
        numberOfProperty[1] = "3";
        numberOfProperty[2] = "4";
        for (int i = 0; i < numberOfProperty.length; i++) {
            bw.write(numberOfProperty[i]);
            bw.newLine();
        }
    }

What's wrong in my code I cannot understand.Compiler shows no error. Please Help. All answer would be appreciated.


Solution

  • public void DataSave() {
        File fout = new File("Data.txt");
        try (FileOutputStream fos = new FileOutputStream(fout); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));) {
            String[] numberOfProperty = new String[3];
            numberOfProperty[0] = "1";
            numberOfProperty[1] = "3";
            numberOfProperty[2] = "4";
            for (String s : numberOfProperty) {
                bw.write(s);
                bw.newLine();
            }
        } catch (IOException ignored) {
    
        }
    }
    

    You need to close the BufferedReader. A better solution is using try-with-resources, so you don't need to worry about closing.

    You can have multiple resources in the try-with-resources separated by a ;.


    Java 13+, you can use Path.of():

    public void DataSave() {
        File fout = new File("Data.txt");
        try (FileOutputStream fos = new FileOutputStream(fout); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));) {
            String[] numberOfProperty = new String[3];
            numberOfProperty[0] = "1";
            numberOfProperty[1] = "3";
            numberOfProperty[2] = "4";
            Files.write(Path.of("Data.txt"), Collections.singletonList(numberOfProperty));
        } catch (IOException ignored) {
    
        }
    }
    

    You can also write your array in one line as:

    String[] numberOfProperty = {"1", "2", "3"};