我有一个java代码,我在读取csv文件时读取csv文件中的String。 我从现有文件创建一个新的csv文件,有2-3列,我可以期待我正在寻找的字符串变量。
以下是我的csv文件
IP,IP2,ID,PID,Abbr
"1.0.0.0","1.0.0.255","16777216","16777471","AU"
"1.0.1.0","1.0.3.255","16777472","CN","16778239"
"1.0.4.0","1.0.7.255","16778240","16779263","AU"
"1.0.8.0","1.0.15.255","16779264","16781311","CN"
"1.0.16.0","1.0.31.255","16781312","16785407","JP"
"1.0.32.0","1.0.63.255","16785408","16793599","CN"
"1.0.64.0","1.0.127.255","16793600","AU","16809983"
"1.0.128.0","1.0.255.255","16842751","AU","16809984"
用于阅读的Java代码
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import au.com.bytecode.opencsv.CSVWriter;
public class CSVFileReader {
public static void main(String[] args) {
CSVFileReader obj = new CSVFileReader();
obj.run();
}
public void run() {
//String csvFile = "whois.csv";
String csvFile="whois.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
String sFileName="whois2.csv";
try {
FileWriter writer = new FileWriter(sFileName); // NOT creating a new FileWriter each time you are writing a line
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(cvsSplitBy);
if(line.contains("AU"))
{
//writer.append(country[4]);
writer.write(country[4]);
writer.write(",");
writer.write(country[3]);
writer.write(",");
System.out.println("Country [code= " + country[2]
+ " , name=" + country[5] + "]");
}
else
{
writer.write("");
writer.write(",");
writer.write("");
writer.write(",");
writer.write("");
writer.append('\n');
System.out.println("");
}
}
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
根据上面的java代码我在上面的字段为AU的whois.csv文件,其中我发现字符串im打印那些列并创建一个新的csv文件。我想要的是当我在比较字符串AU时创建一个新文件使用我的csv内容,我想在原始文件中的新文件althogh中的一列中列出所有AU内容列值,AU字符串值在不同的列中。 就像AU字符串存在于第一行和最后两行,这个csv文件将来可能会更长。但是我不确定该字符串是否为此字符串。所以我在新的csv文件中插入可疑行。但是在新的csv文件中,我只想要一个包含所有AU字符串列值的列,无论它们是在第三列,第四列还是任何其他列中,AU将仅出现在csv文件的每一行中的一列中... 请指导一下......
答案 0 :(得分:0)
将此代码放在您希望它开始写出连接字段值的位置,它将在一列中写入包含AU的当前行的所有字段值。
for (String field : country)
if(line.contains("AU"))
writer.write(field);