2017-07-28 83 views
-1

我想要做的很簡單的事情 - 保存文件中的字符串。但由於某種原因,它只保存了前66個字符。我嘗試了很多不同的代碼,但沒有任何實際工作。我當前的代碼:使用OutputStreamWriter類寫入文件像在txt文件中的Android-保存字符串

final String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath(); 
    File dir = new File(dirPath); 
    if(!dir.exists()) 
     dir.mkdirs(); 
    File file = new File(dirPath, "file.txt"); 
    FileOutputStream stream = null; 
    try { 
     stream = new FileOutputStream(file); 

     stream.write(myString); 
     stream.flush(); 
     stream.close(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      if (stream != null) { 
       stream.close(); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
+0

什麼樣的錯誤你得到 – Alok

回答

2

嘗試:

try 
{ 
    file.createNewFile(); 
    FileOutputStream fOut = new FileOutputStream(file); 
    OutputStreamWriter outWriter = new OutputStreamWriter(fOut); 
    outWriter.append(data); 

    outWriter.close(); 

    fOut.flush(); 
    fOut.close(); 
} 
catch (IOException e) 
{ 
    Log.e("Exception", "File write failed: " + e.toString()); 
} 
+0

它的工作。謝謝! –