2013-10-13 28 views

回答

0

只需讀取csv文件字段並更改/編輯並將所有字段保存到另一個csv文件。

舉例來說,如果我有一個CSV文件(user.csv)和該文件包含2列usernamepassword,我想更新的領域,編碼是在這裏:

String text = null; 
string filename="user.csv"; 
     try { 
      FileInputStream fis = new FileInputStream(filename); 
      DataInputStream myInput = new DataInputStream(fis); 
      while ((text = myInput.readLine()) != null) { 
       // System.out.println(text); 

       String[] strar = text.split(","); 
       String username = strar[0]; 
       String password = strar[1]; 
       // so here you can update both username and password and save into another 
csv file 
    string write=username +","+password ; 
WriteToCsv(write); 

        } 
} catch (IOException ex) { 
      ex.printStackTrace(); 
    enter code here 

//save into csv file here 
public static synchronized void WriteToCsv(String s) { 
     PrintWriter pw = null; 
     try { 
      File f = new File(newfile); 
      pw = new PrintWriter(new FileWriter(f, true)); 
      pw.println(s); 
      pw.flush(); 
      pw.close(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } finally { 
      pw.close(); 
     } 
    } 
相關問題