2012-02-28 55 views
0

我正在創建一個類來管理文本文件。我必須寫一個方法和其他閱讀我的文件:「已解決」末尾帶空格的寫入文件

public static void writeFiles(Context context, String nomFichier, String content, char mode) { 

    FileOutputStream fOut = null; 
    OutputStreamWriter osw = null; 

    try { 
     if (mode == 'd') { 
      context.deleteFile(nomFichier); 
     } else {   
      fOut = context.openFileOutput(nomFichier, Context.MODE_APPEND);  
      osw = new OutputStreamWriter(fOut); 
      osw.write(content); 
      osw.flush(); 
     } 
    } catch (Exception e) {  
     Toast.makeText(context, "Message not saved",Toast.LENGTH_SHORT).show(); 
    } finally { 
     try { 
      osw.close(); 
      fOut.close(); 
     } catch (IOException e) { 
      Toast.makeText(context, "Message not saved",Toast.LENGTH_SHORT).show(); 
     } 
    } 
} 

當我創建一個文件,它充滿了一些空行。我想將我的文件的內容設置爲EditText,所以我不需要空白。 如何創建一個沒有空白的文件?

Thx,korax。

編輯:

我使用TRIM(),由appserv和公務機的建議,但在讀取功能,而不是寫功能。它工作正常,thx你!

public static String readFile(Context context, String fileName) { 

    FileInputStream fIn = null; 
    InputStreamReader isr = null; 
    char[] inputBuffer = new char[255]; 
    String content = null; 

    try { 
     fIn = context.openFileInput(fileName);  
     isr = new InputStreamReader(fIn); 
     isr.read(inputBuffer); 
     content = new String(inputBuffer); 
    } catch (Exception e) {  
     //Toast.makeText(context, "Message not read",Toast.LENGTH_SHORT).show(); 
    } 
    finally { 
     try {    
      isr.close(); 
      fIn.close(); 
     } catch (IOException e) { 
      //Toast.makeText(context, "Message not read",Toast.LENGTH_SHORT).show(); 
     } 
    } 
    return content.trim(); 
} 
+0

嘗試osw.write(content.trim()); – 2012-02-28 19:54:05

+0

Thx你,它的工作! – korax 2012-02-29 00:25:37

回答

0

如果使用文本編輯器創建文件,編輯器可能會添加一些空行來填充文件大小。您可以調用openFileOutput而不使用MODE_APPEND標誌以編程方式創建新(空)文件,從而避免了文本編輯器。

否則,appserv的建議使用trim()應該很好地清理字符串。

+0

Thx你,我用修剪(),它的工作原理! – korax 2012-02-29 00:26:04