2016-12-14 56 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的代码,它的工作完美,是的文本文件需要包含多行。 –

相关问题