求个java读取csv文件并输出的程序
输出的结果第1行是csv的第1列的第1行,回车后第2行是csv的第1列的前两行,下一行是第1列的前3行,以此类推到第1列结束后,下一行是前两列的第1行,然后是前两列的前两...
输出的结果第1行是csv的第1列的第1行,回车后第2行是csv的第1列的前两行,下一行是第1列的前3行,以此类推到第1列结束后,下一行是前两列的第1行,然后是前两列的前两行,直到最后。想象的结果应该是这样:
1
---
1
2
---
1
2
3
---
11
---
11
22
---
11
22
33
---
111
---
111
222
在控制台输出 展开
1
---
1
2
---
1
2
3
---
11
---
11
22
---
11
22
33
---
111
---
111
222
在控制台输出 展开
2个回答
展开全部
要使用CsvReader,CsvWriter需要下载一个javacsv.jar导入到项目中
package test;import com.csvreader.CsvReader;import com.csvreader.CsvWriter;import java.io.BufferedReader; import java.io.BufferedWriter;import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter;import java.io.IOException; public class readandwrite { public static void main(String[] args) throws IOException { String [] str ={"省","市","区","街","路","里","幢","村","室","园","苑","巷","号"}; String inString = ""; String tmpString = ""; File inFile = new File("C://in.csv"); // 读取的CSV文件 File outFile = new File("C://outtest.csv");//输出的CSV文 try { BufferedReader reader = new BufferedReader(new FileReader(inFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); CsvReader creader = new CsvReader(reader, ','); CsvWriter cwriter = new CsvWriter(writer,','); while(creader.readRecord()){ inString = creader.getRawRecord();//读取一行数据 for(int i = 0;i < str.length;i++){ tmpString = inString.replace(str[i], "," + str[i] + ","); inString = tmpString; } //第一个参数表示要写入的字符串数组,每一个元素占一个单元格,第二个参数为true时表示写完数据后自动换行 cwriter.writeRecord(inString.split(","), true); //注意,此时再用cwriter.write(inString)方法写入数据将会看到只往第一个单元格写入了数据,“,”没起到调到下一个单元格的作用 //如果用cwriter.write(String str)方法来写数据,则要用cwriter.endRecord()方法来实现换行 //cwriter.endRecord();//换行 cwriter.flush();//刷新数据 } creader.close(); cwriter.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } }}
追问
抱歉,描述没说好,输出在控制台就可以,不用在新csv文件里
追答
public static void main(String[] args) throws IOException {
String [] str = {"省","市","区","街","路","里","幢","村","室","园","苑","巷","号"};
String inString = "";String tmpString = "";
File inFile = new File("C://in.csv"); // 读取的CSV文件
try {
BufferedReader reader = new BufferedReader(new FileReader(inFile));
CsvReader creader = new CsvReader(reader, ',');
while(creader.readRecord()){
inString = creader.getRawRecord();//读取一行数据
for(int i = 0;i < str.length;i++){
tmpString = inString.replace(str[i], "," + str[i] + ",");
System.out.println(tmpString);
}
} creader.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} }
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询