Java - 逐行写入字符串到文件一行/不能将字符串转换为字符串[]

时间:2017-09-14 02:26:42

标签: java string

编程相对较新。我想读取一个URL,修改文本字符串,然后将其写入以行分隔的csv文本文件。

阅读&修改零件运行。此外,将字符串输出到终端(使用Eclipse)看起来很好(csv,逐行),像这样;

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

但是我无法将相同的字符串写入文件 - 它只是一个单行(请参阅下面的for-loops,尝试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);
}

2 个答案:

答案 0 :(得分:2)

在for循环之前创建BufferedWriterFileWriter,而不是每次都围绕它。

答案 1 :(得分: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) {}