1

Here is an example where I read lines from a file as strings to make a whole file as an array of strings:

String[] ArrayOfStrings = (new Scanner( new File("log.txt") ).useDelimiter("\\A").next()).split("[\\r\\n]+");

I there any similar way to do the write back into the file:

something_that_writes_into_file(ArrayOfStrings)?

I know about PrintWriter, Buffer and other stuffs using loops.

My question is specifically about something which is more compact, say - a one line solution?

tod
  • 1,539
  • 4
  • 17
  • 43

3 Answers3

1

Using Apache Commons IO and Apache StringUtils:

FileUtils.writeStringToFile(new File(theFile), StringUtils.join(theArray, delimiter));
Danstahr
  • 4,190
  • 22
  • 38
0

This is how it can be done.

for(int i = 0; i < observation.length; i++)
{
    try(BufferedWriter bw = new BufferedWriter(new FileWriter("birdobservations.txt", true)))
    {
        String s;
        s = observation[i];
        bw.write(s);
        bw.flush();
    }
    catch(IOException ex)
    {
        //
    }
}

Same question is discussed before, Please refer below link for the same. Writing a string array to file using Java - separate lines

Community
  • 1
  • 1
Varun
  • 583
  • 5
  • 12
0

In Java8 one might use Streams:

File file = new File("log.txt");
FileWriter out = new FileWriter(file);

// reading
String[] arrayOfStrings = (new Scanner(file).useDelimiter("\\A").next()).split("[\\r\\n]+");

// writing
Stream.of(arrayOfStrings).forEach(e -> {try {out.append(e);} catch (IOException e1) {e1.printStackTrace();}});

Of couse this is very bad style and I only wrote it that way, because you requested a "1-liner". Actually it would be done like so:

Stream.of(arrayOfStrings).forEach(e -> {
    try {
        out.append(e);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
});
ifloop
  • 8,079
  • 2
  • 26
  • 35