使用扫描仪读取CSV() [英] Read CSV with Scanner()
本文介绍了使用扫描仪读取CSV()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的csv正在读入System.out,但我注意到任何带空格的文本都会被移动到下一行(作为返回\ n)
My csv is getting read into the System.out, but I've noticed that any text with a space gets moved into the next line (as a return \n)
以下是我的csv如何开始:
Here's how my csv starts:
first,last,email,address 1, address 2
john,smith,blah@blah.com,123 St. Street,
Jane,Smith,blech@blech.com,4455 Roger Cir,apt 2
运行我的应用程序后,任何有空格(地址1)的单元格都会被抛到下一行。
After running my app, any cell with a space (address 1), gets thrown onto the next line.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
// -define .csv file in app
String fileNameDefined = "uploadedcsv/employees.csv";
// -File class needed to turn stringName to actual file
File file = new File(fileNameDefined);
try{
// -read from filePooped with Scanner class
Scanner inputStream = new Scanner(file);
// hashNext() loops line-by-line
while(inputStream.hasNext()){
//read single line, put in string
String data = inputStream.next();
System.out.println(data + "***");
}
// after loop, close scanner
inputStream.close();
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
所以这里是控制台中的结果:
So here's the result in the console:
first,last,email,address
1,address
2
john,smith,blah@blah.com,123
St.
Street,
Jane,Smith,blech@blech.com,4455
Roger
Cir,apt
2
我是否错误地使用了扫描仪?
Am I using Scanner incorrectly?
推荐答案
scanner.useDelimiter(",");
这应该有效。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TestScanner {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("/Users/pankaj/abc.csv"));
scanner.useDelimiter(",");
while(scanner.hasNext()){
System.out.print(scanner.next()+"|");
}
scanner.close();
}
}
对于CSV文件:
a,b,c d,e
1,2,3 4,5
X,Y,Z A,B
输出为:
a|b|c d|e
1|2|3 4|5
X|Y|Z A|B|
这篇关于使用扫描仪读取CSV()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文