2012-02-28 71 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