[英]One-liner to count number of occurrences of String in a String[] in Java?
[英]Java - write string to file line by line vs one-liner / cannot convert String to String[]
对编程而言相对较新。 我想读取一个URL,修改文本字符串,然后将其写入以行分隔的csv文本文件。
读取和修改部件开始运行。 同样,将字符串输出到终端(使用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转换为String []”的错误。 有什么建议么?
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);
}
在for循环之前而不是每次都创建BufferedWriter
和FileWriter
。
从您的代码注释中, 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) {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.