我有一个文本文件,其中包含以下内容。 我试图测试我的代码,并注意到我为我的扫描器输入的文件只包含一行。为什么是这样呢?当我打开文本文件时,它出现了多行。如何更改文本文件,使其包含多行?
当我打开这是excel,它显示多行然而,当我编程时,它会显示所有这一切在一行。我怎样才能改变这种文件结构,使得它具有多行
文本文件:
categories
Fast Food;Restaurants
Nightlife
Active Life;Mini Golf;Golf
Bars;American (New);Nightlife;Lounges;Restaurants
Active Life;Golf
Bars;American (Traditional);Nightlife;Restaurants
Auto Repair;Automotive;Tires
Active Life;Mini Golf
Roofing;Home Services;Decks & Railing;Contractors
Veterinarians;Pets
Libraries;Public Services & Government
Automotive;Auto Parts & Supplies
Burgers;Breakfast & Brunch;American (Traditional);Restaurants
Food;Grocery
Automotive;Gas & Service Stations
Local Services;Dry Cleaning & Laundry;Sewing & Alterations
Automotive;Gas & Service Stations
Bars;American (Traditional);Nightlife;Lounges;Restaurants
Breakfast & Brunch;Sandwiches;Restaurants
Cafes;Restaurants
Hotels & Travel;Event Planning & Services;Hotels
Pubs;Irish;Nightlife;Bars;Restaurants
Pizza;Restaurants
Local Services;Sewing & Alterations
Restaurants
Health & Medical;Dentists;General Dentistry
Chinese;Restaurants
Veterinarians;Pets
代码:
public class TestScanner {
public static void main(String[] args) throws FileNotFoundException {
int count = 0;
Scanner scanner = new Scanner(new File("C:/data/test3.txt"));
scanner.useDelimiter(";");
while(scanner.hasNextLine()){
System.out.print(scanner.nextLine());
count++;
}
scanner.close();
System.out.println(count);
}
}
输出:1
你的代码就好了。我怀疑你的test3文件只有一个空行。请验证这一点。 – Thrasher
也许你的文本编辑器正在使用自动换行。在记事本++上打开你的txt文件,并去查看>符号>显示所有字符。这将向您显示您的文件是否包含记录分隔符,即\ n(LF)或\ r \ n(CRLF)。 – rafaelbattesti
你的代码工作正常! –