2015-08-25 68 views
0

如何在現有文件中逐一添加數據?正在使用以下代碼..在文件中追加數據行順序..如何解決這個問題?如何在Android中的現有文件中逐個追加數據?

private String SaveText() { 

    File sdCard = Environment.getExternalStorageDirectory(); 
    File dir = new File (sdCard.getAbsolutePath()+File.separator+"GPS"); 
    dir.mkdirs(); 

    String fname = "gps.txt"; 
    File file = new File (dir, fname); 

    FileOutputStream fos; 
    try { 

     fos = new FileOutputStream(file,true); 
     OutputStreamWriter out=new OutputStreamWriter(fos); 
     out.write(value1); 
     out.close(); 
     fos.close(); 

     Toast.makeText(getApplicationContext(), "Saved lat,long", Toast.LENGTH_SHORT).show(); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return dir.getAbsolutePath(); 
} 
+0

如果您使用的是Java 7,您可以使用您的代碼做工精細嘗試'Files.write ...()' – Rustam

回答

0

試試這個代碼

try{ 

     OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file,true), "UTF-8"); 
     BufferedWriter fbw = new BufferedWriter(writer); 
     fbw.write(value1); 
     fbw.newLine(); 
     fbw.close(); 
     Toast.makeText(getApplicationContext(), "Saved lat,long", Toast.LENGTH_SHORT).show(); 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
    } 
+0

上午,但相同的值存儲在一個接一個,這就是爲什麼? – Mani

+0

fbw.newLine();所以如果你滿意答案 – sasikumar

+0

存儲一個,點擊+1的帖子 – sasikumar

-1

JAVA 7你可以試試:

 try { 

      Files.write(Paths.get(dir+File.separator+fname), latLng.getBytes(), StandardOpenOption.APPEND); 

      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

結賬美麗的解釋:here

+1

Android是Java 6的基礎,並沒有'java.nio.file' –

0

複製並粘貼此代碼。

public void SaveText(String sFileName, String sBody){ 
try 
{ 
    File root = new File(Environment.getExternalStorageDirectory(), "Notes"); 
    if (!root.exists()) { 
     root.mkdirs(); 
    } 
    File gpxfile = new File(root, sFileName); 
    FileWriter writer = new FileWriter(gpxfile); 
    writer.append(sBody); 
    writer.flush(); 
    writer.close(); 
    Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show(); 
} 
catch(IOException e) 
{ 
    e.printStackTrace(); 
    importError = e.getMessage(); 
    iError(); 
}} 
相關問題