2011-09-07 54 views
1

我正在嘗試創建一個能夠將文本寫入黑莓文本文件的應用程序。我能夠在文本文件中寫入文本,但是當我嘗試寫入新的文本行時,它只是覆蓋了我之前寫入的文本。誰能幫我?我試圖尋找圍繞論壇,但沒有人有我需要的具體解決方案。如何使用OutputStream將新行插入到Blackberry的文本文件中?

下面是我的代碼:

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

請幫助我。 :(

回答

3

看起來你正在爲向量中的每個項目的新文件,嘗試在循環移動僅包圍寫操作:

.---- 
|  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()); 
|  } 
| } 
'-- 
+0

謝謝!!!!!!!! !!!!真的解決了我的問題,非常感謝!!!:D:D:D真的對我有幫助:D – TEN

+0

呵呵,沒問題,不客氣:-) – aioobe

相關問題