[英]How do I read a text/CSV file and ignore the "\n" in java
I am using bufferedreader to capture the text in a CSV file and a Scanner to assign it to a variable so I can save it to an array later, the file has three values, a number, a name, and a "price" but when I read the "price" it captures the "price" \n number which throws off everything, how do I stop reading \n without using ".nextLine" The code looks like this我正在使用 bufferedreader 来捕获 CSV 文件中的文本,并使用 Scanner 将其分配给变量,以便稍后将其保存到数组中,该文件具有三个值,一个数字,一个名称和一个“价格” ,但是当我读了“价格”,它捕获了“价格”\n 数字,它抛出了一切,我如何停止阅读 \n 而不使用“.nextLine” 代码看起来像这样
try {
File file = new File("...\\file.csv");
FileReader printReader = new FileReader(file);
BufferedReader BuffReader = new BufferedReader(printReader);
Scanner Writer = new Scanner(BuffReader);
//get max number of iteams in the file
Writer.useDelimiter(",");
String num = Writer.next();
int max=Integer.parseInt(num);
System.out.println(num + " Max");
/*start Random
Random rand = new Random();
int min;
min = 1;
int Amount = rand.nextInt((max - min) + 1) + min;
System.out.println(Amount + " Amount");*/
String Item = Writer.next(); //get the name of the iteam
System.out.println(Item + " Item1"); //print item
String Price = Writer.next(); ///get price of the item...this is were the error occurs
System.out.println(Price + " Price1"); //print price
num = Writer.next(); //Suppose to get the number of the item
int Num=Integer.parseInt(num); //conver to an int
System.out.println(Num + " Num");
Item = Writer.next();
System.out.println(Item + " Item2");
Price = Writer.next();
System.out.println(Price + " Price2");
BuffReader.close();
Writer.close();
}
the example for the CSV/txtfile is CSV/txt 文件的示例是
116,item,Price 116,项目,价格
1,item2,price2 1,项目2,价格2
2,item3,price 2,项目3,价格
my goal is to choose a random item from this list using a util.Random, and checking what number it is using the first number in the txt file and saving the team and price to an array我的目标是使用 util.Random 从该列表中选择一个随机项目,并使用 txt 文件中的第一个数字检查它是什么数字,并将团队和价格保存到一个数组中
You can use \n
as an additional delimiter besides ,
.除了 , 之外,
您还可以使用\n
作为附加分隔符。 Simply change this line of code:只需更改这行代码:
Writer.useDelimiter(",");
to this one:对此:
Writer.useDelimiter("(,|\n)");
With this next()
reads three values in each line and does not combine the last and first value of two lines.有了这个next()
读取每行中的三个值,并且不组合两行的最后一个值和第一个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.