2017-09-14 89 views
0

編程相對較新。我想讀取一個URL,修改文本字符串,然後將其寫入行分隔的csv文本文件。Java - 將字符串逐行寫入文件vs單行/無法將字符串轉換爲字符串[]

閱讀&修改部件運行。另外,輸出字符串到終端(使用Eclipse)看起來很好(csv,逐行),像這樣;

data_a,data_b,data_c,... 
data_a1,data_b1,datac1... 
data_a2,data_b2,datac2... 
. 
. 
. 

但我不能寫同一個字符串的文件 - 它只是變成一個班輪(見下面我的for循環,嘗試沒有1 & 2);

data_a,data_b,data_c,data_a1,data_b1,datac1,data_a2,data_b2,datac2... 

我想我正在尋找一種方式,在FileWriter的或循環的BufferedWriter,串finalDataA轉換爲字符串數組(即包含字符串後綴「[0]」),但我還沒有找到這種方法不會給出「不能將字符串轉換爲字符串[]」類型的錯誤。有什麼建議麼?

String data = ""; 
    String dataHelper = ""; 
    try { 
     URL myURL = new URL(url); 
     HttpURLConnection myConnection = (HttpURLConnection) myURL.openConnection(); 
     if (myConnection.getResponseCode() == URLStatus.HTTP_OK.getStatusCode()) { 
      BufferedReader in = new BufferedReader(new InputStreamReader(myConnection.getInputStream())); 

      while ((data = in.readLine()) != null) { 
        dataHelper = dataHelper + "\n" + data; 
      } 
      in.close(); 

      String trimmedData = dataHelper.trim().replaceAll(" +", ","); 
      String parts[] = trimmedData.split(Pattern.quote(")"));// ,1.,"); 
      String dataA = parts[1]; 
      String finalDataA[] = dataA.split("</PRE>"); 
      // parts 2&3 removed in this example 

      // Console output for testing purpose - This prints out many many lines of csv-data 
      System.out.println(finalDataA[0]); 
      //This returns the value 1 
      System.out.println(finalDataA.length); 

      // Attempt no. 1 to write to file - writes a oneliner 
      for(int i = 0; i < finalDataA.length; i++) { 
       try (BufferedWriter bw = new BufferedWriter(new FileWriter(pathA, true))) { 
        String s; 
        s = finalDataA[i]; 
        bw.write(s); 
        bw.newLine(); 
        bw.flush(); 
       } 
      } 

      // Attempt no. 2 to write to file - writes a oneliner 
      FileWriter fw = new FileWriter(pathA); 
      for (int i = 0; i < finalDataA.length; i++) { 
       fw.write(finalDataA[i] + "\n"); 
      } 
      fw.close(); 

     } 
    } catch (Exception e) { 
     System.out.println("Exception" +e); 
} 

回答

0

從你的代碼註釋中,finalDataA有一個元素,所以for循環只會執行一次。嘗試將finalDataA[0]拆分成行。 類似這樣的:

String endOfLineToken = "..."; //your variant 
    String[] lines = finalDataA[0].split(endOfLineToken) 
    BufferdWriter bw = new BufferedWriter(new FileWriter(pathA, true)); 
    try 
    { 
     for (String line: lines) 
     { 
      bw.write(line); 
      bw.write(endOfLineToken);//to put back line endings 
      bw.newLine(); 
      bw.flush(); 
     } 
    } 
    catch (Exception e) {} 
+0

這會在每行寫入兩行結束符。你不需要'write(endOfLineToken)'*和*'newLine()'。 'newLine()'就足夠了。 – EJP

+0

@EJP名稱endOfLineToken可能會令人困惑,但它應該從使用中顯而易見,這不是必需的「\ n」或CR或其他。它應該爲未分析數據中的行分隔。 –

+0

這個訣竅 - 非常感謝羅馬! –

2

創建BufferedWriterFileWriter領先的for循環,而不是圍繞它的每一次。