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?

3 Answers 3

1

Using Apache Commons IO and Apache StringUtils:

FileUtils.writeStringToFile(new File(theFile), StringUtils.join(theArray, delimiter));
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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();
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.