如何更改文本文件以使其包含多行?

时间:2016-12-14 04:03:33

标签: java file input file-io java.util.scanner

我有一个包含以下内容的文本文件。 我试图测试我的代码,并注意到我为扫描仪输入的文件只包含一行。为什么会这样?,当我打开文本文件时,它看起来有多行。

当我打开这是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

1 个答案:

答案 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);

它会将文本文件视为多行文本。