简体   繁体   中英

How to write or append string in loop in a file in java?

I'm having memory problem as working with very large dataset and getting memory leaks with char[] and Strings, don't know why! So I am thinking of writing some processed data in a file and not store in memory. So, I want to write texts from an arrayList in a file using a loop. First the program will check if the specific file already exist in the current working directory and if not then create a file with the specific name and start writing texts from the arrayList line by line using a loop; and if the file is already exist then open the file and append the 1st array value after the last line(in a new line) of the file and start writing other array values in a loop line by line.

Can any body suggest me how can I do this in Java? I'm not that good in Java so please provide some sample code if possible.

Thanks!

Try this

ArrayList<String> StringarrayList = new ArrayList<String>(); 
    FileWriter writer = new FileWriter("output.txt", true); 
    for(String str: StringarrayList ) {
      writer.write(str + "\n");
    }
    writer.close();

I'm not sure what parts of the process you are unsure of, so I'll start at the beginning.

The Serializable interface lets you write an object to a file. Any object that implemsents Serializable can be passed to an ObjectOutputStream and written to a file.

ObjectOutputStream accepts a FileOutputStream as argument, which can append to a file.

ObjectOutputstream outputStream = new ObjectOutputStream(new FileOutputStream("filename", true));
outputStream.writeObject(anObject);

There is some exception handling to take care of, but these are the basics. Note that anObject should implement Serializable .

Reading the file is very similar, except it uses the Input version of the classes I mentioned.

// in main

List<String> SarrayList = new ArrayList<String>(); 
.....

fill it with content

enter content to SarrayList here .....

write to file

appendToFile (SarrayList);

.....

public void appendToFile (List<String> SarrayList) {

      BufferedWriter bw = null;
      boolean myappend = true;
      try {
         bw = new BufferedWriter(new FileWriter("myContent.txt", myappend));
         for(String line: SarrayList ) {
         bw.write(line);
         bw.newLine();
         }
         bw.flush();
      } catch (IOException ioe) {
        ioe.printStackTrace();
      } finally { 
        if (bw != null) try {
        bw.close();
        } catch (IOException ioe2) {
        // ignore it  or write notice
        }
      }

   } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM