How to insert a new line into the text file for Blackberry using OutputStream?
I am trying to create an application that is able to write text into text file in Blackberry. I am able to write text inside the text file, but when I try to write a new line of text, it just overwrites the text I write into previously. Can anyone help me? I try to look for the forums around but no one has the specific solution that I needed.
Below is my code:
package filepackage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import net.rim.device.api.io.File;
import net.rim.device.api.system.Application;
public class WritingText extends Application{
/**
* Entry point for application
* @param args Command line arguments (not used)
*/
public static void main(String[] args){
WritingText app = new WritingText();
app.setAcceptEvents(false);
Vector v = new Vector();
v.addElement("Test2seconds.mp3");
v.addElement("Test2seconds2.mp3");
v.addElement("Test2seconds3.mp3");
v.addElement("Test2seconds4.mp3");
v.addElement("blind_willie.mp3");
for(int i=0;i<v.size();i++){
try
{
FileConnection fc = (FileConnection)Connector.open("file:///SDCard/newfile.txt");
// If no exception is thrown, then the URI is valid, but the file may or may not exist.
if (!fc.exists())
{
fc.create(); // create the file if it doesn't exist
}
OutputStrea开发者_如何学Cm outStream = fc.openOutputStream();
outStream.write(((String) v.elementAt(i)).getBytes());
String br = "\r\n";
outStream.write (br.getBytes ());
outStream.close();
fc.close();
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage() );
}
}
}
}
Please help me. :(
Looks like you're creating a new file for each item in the vector. Try moving in the loop to surround only the write-operations:
.----
| try
| {
| FileConnection fc = (FileConnection)Connector.open(...);
| // If no exception is thrown, then the URI is valid
| if (!fc.exists())
| {
| fc.create(); // create the file if it doesn't exist
| }
| OutputStream outStream = fc.openOutputStream();
|
'--> for(int i=0;i<v.size();i++){
outStream.write(((String) v.elementAt(i)).getBytes());
String br = "\r\n";
outStream.write (br.getBytes ());
.--> }
|
| outStream.close();
| fc.close();
| }
| catch (IOException ioe)
| {
| System.out.println(ioe.getMessage() );
| }
| }
'--
精彩评论