我有一個文本文件,其中包含以下內容。 我試圖測試我的代碼,並注意到我爲我的掃描器輸入的文件只包含一行。爲什麼是這樣呢?當我打開文本文件時,它出現了多行。如何更改文本文件,使其包含多行?
當我打開這是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
你的代碼工作正常! –