0

I want to write some texts in a new line into an existing file.I tried following code but failed,Can any one suggest how can I append to file in a new row.

private void writeIntoFile1(String str) {
    try {
        fc=(FileConnection) Connector.open("file:///SDCard/SpeedScence/MaillLog.txt");
        OutputStream os = fc.openOutputStream(fc.fileSize());
        os.write(str.getBytes());
        os.close();
        fc.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

and calling

writeIntoFile1("aaaaaaaaa");
writeIntoFile1("bbbbbb");

Its successfully writing to the file I simulated(SDCard) but its appears in the same line. How can I write "bbbbbb" to new line?

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
Jisson
  • 3,566
  • 8
  • 38
  • 71

1 Answers1

1

Write a newline (\n) after writing the string.

private void writeIntoFile1(String str) {
    try {
        fc = (FileConnection) Connector.open("file:///SDCard/SpeedScence/MaillLog.txt");
        OutputStream os = fc.openOutputStream(fc.fileSize());
        os.write(str.getBytes());
        os.write("\n".getBytes());
        os.close();
        fc.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

N.B. a PrintStream is generally better-suited for printing text, though I'm not familiar enough with the BlackBerry API to know if it's possible to use a PrintStream at all. With a PrintStream you'd just use println():

private void writeIntoFile1(String str) {
    try {
        fc = (FileConnection) Connector.open("file:///SDCard/SpeedScence/MaillLog.txt");
        PrintStream ps = new PrintStream(fc.openOutputStream(fc.fileSize()));
        ps.println(str.getBytes());
        ps.close();
        fc.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • Matt Ball, Still I have the same problem – Jisson May 13 '11 at 14:11
  • @Jisson I'm not familiar with the platform - you might need to use `\r\n` instead of `\n` for it to appear properly. – Matt Ball May 13 '11 at 14:14
  • BlackBerry does support PrintStream. http://www.blackberry.com/developers/docs/4.0.2api/java/io/PrintStream.html – Swati May 13 '11 at 15:36
  • @Swati: thanks. I took a glance at the `FileConnection` interface but didn't see any way to get a `PrintStream` instead of a vanilla `OutputStream`, so I wasn't sure if it would work in this specific case. – Matt Ball May 13 '11 at 15:55
  • You can create the PrintStream by just passing it the OutputStream. i.e. PrintStream ps = new PrintStream(outputStream); – Swati May 13 '11 at 16:15
  • @Swati: d'oh, of course! I'll update my answer. Thanks again. – Matt Ball May 13 '11 at 16:17