3
我讀一個CSV文件,並有一定的價值像
field 1 field 2 field 3
1 test case1 expecting one, and \"two\", and three
讀文件到StringBuilder
和轉換toString()
後,我通過分割文件內容。
在遍歷字符串我得到這些值: -
1
test case1
expecting one, and ""two"", and three
我如何我喜歡單,雙替換兩個雙引號這個「二」
這裏是我的代碼: -
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class csvStringParser {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String path = "E:/spc.csv";
String read = readFile(path);
System.out.println("content of the file before \" = \n" +read);
// System.out.println("content of the file after= \n" +read);
String[] tokens = read.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
for(int i = 0;i<tokens.length;i++) {
String abc = tokens[i].replace("\"\"", "\"");
// if(abc.length()>2){
if(abc.startsWith("\"") && abc.endsWith("\"")){
abc = abc.substring(1, abc.length()-1);
}
// }
System.out.println("> "+abc);
}
}
public static String readFile(String file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
return stringBuilder.toString();
}
}
不工作對我來說,如果我寫串讀= READFILE(路徑); read.replace(「\」\「」,「\」「); – user1371033 2012-08-09 19:37:54
您是否看到我的代碼?有沒有什麼我做錯了? – user1371033 2012-08-09 19:47:58
我現在看到它了,不,我沒有看到明顯的東西。你能整理一個ideone的例子嗎? – 2012-08-09 19:50:06