2012-02-16 39 views
5

我正嘗試在android中向文本文件寫入新行。Android不會在文本文件中寫入新行

這裏是我的代碼:

FileOutputStream fOut; 
try { 
    String newline = "\r\n"; 
    fOut = openFileOutput("cache.txt", MODE_WORLD_READABLE); 
    OutputStreamWriter osw = new OutputStreamWriter(fOut); 

    osw.write(data); 
    osw.write(newline); 

    osw.flush(); 
    osw.close(); 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

我已經試過\n\r\n我也還試圖讓系統性能的一個新行,他們都沒有工作。

數據變量包含之前來自同一文件的數據。

String data = ""; 

try { 
    FileInputStream in = openFileInput("cache.txt"); 
    StringBuffer inLine = new StringBuffer(); 
    InputStreamReader isr = new InputStreamReader(in, "ISO8859-1"); 
    BufferedReader inRd = new BufferedReader(isr,8 * 1024); 
    String text; 

    while ((text = inRd.readLine()) != null) { 
     inLine.append(text); 
    } 

    in.close(); 
    data = inLine.toString(); 
} catch (FileNotFoundException e1) { 
    e1.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
+0

你是什麼意思「不工作」?你如何檢查它?還可以嘗試用'foo'等簡單的東西替換'data'並檢查變量內容 – 2012-02-16 13:46:17

+0

當我在textedit,word或其他程序中打開它時,新行不會顯示 – NikolajSvendsen 2012-02-16 13:47:57

+0

嘗試使用虛擬文本,它不會顯示w掃。 – NikolajSvendsen 2012-02-16 13:59:20

回答

0

我執行了一個類似的程序,它爲我工作。我觀察到一個奇怪的行爲,但。它將這些新行添加到文件中,但光標保留在第一行。如果要驗證,請在換行符後面寫一個String,您會看到String寫在這些新行的下方。

0

我有同樣的問題,無法寫一個換行符。相反,我使用BufferdWritter在文件中寫入新行,它適用於我。 下面是一個示例代碼sniplet:

OutputStreamWriter out = new OutputStreamWriter(openFileOutput("cache.txt",0)); 
BufferedWriter bwriter = new BufferedWriter(out); 
// write the contents to the file 
bwriter.write("Input String"); //Enter the string here 
bwriter.newLine(); 
2

我有同樣的問題,試圖在書中每招。

我的問題:換行的寫,但是在讀他們被拆除:

while (readString != null) { 
       datax.append(readString); 
       readString = buffreader.readLine(); 
      } 

該文件讀取線和級聯線,所以換行的消失。

我沒有看在記事本中的原始文件或東西,因爲我不知道去哪裏找我的電話,我的logscreen使用哪種去除換行符的:-(

那麼簡單soultion代碼在閱讀時將它放回原處:

while (readString != null) { 
       datax.append(readString); 
       datax.append("\n"); 
       readString = buffreader.readLine(); 
      }