2017-09-14 88 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循环,而不是围绕它的每一次。