2016-12-14 31 views
0

我有一個文本文件,其中包含以下內容。 我試圖測試我的代碼,並注意到我爲我的掃描器輸入的文件只包含一行。爲什麼是這樣呢?當我打開文本文件時,它出現了多行。如何更改文本文件,使其包含多行?

當我打開這是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

+0

你的代碼就好了。我懷疑你的test3文件只有一個空行。請驗證這一點。 – Thrasher

+1

也許你的文本編輯器正在使用自動換行。在記事本++上打開你的txt文件,並去查看>符號>顯示所有字符。這將向您顯示您的文件是否包含記錄分隔符,即\ n(LF)或\ r \ n(CRLF)。 – rafaelbattesti

+0

你的代碼工作正常! –

回答

-1

你不改變文本文件。可能你需要更改代碼。試試這個:

FileReader fileReader = new FileReader("C:/data/test3.txt"); 
LineNumberReader lineNumberReader = new LineNumberReader(fileReader); 
String tmp = null; 
while ((tmp = lineNumberReader.readLine()) != null) { 
    count++; 
    System.out.println(tmp); 
} 

lineNumberReader.close(); 
System.out.println(count); 

它會將文本文件視爲多行文本。

+0

我猜OP的問題在文本文件中。如果文件中沒有多行文本,則說明您的方法不起作用。否則,任何讀者都可以滿足OP的需要。 –

+0

@WasiAhmad我運行了OP的代碼和文本文件。事實上,它給了我一條線。然後我改變了完全相同的文本輸入的代碼,它給了多行。順便說一句,該文本文件是在多行。 – Nurjan

+0

我跑OP的代碼,它的工作完美,是的文本文件需要包含多行。 –

相關問題