2013-01-09 105 views
7

我幾乎沒有使用分隔符的經驗,我需要讀取一個文本文件,該文件存儲數據以逗號(「,」)分隔的單行存儲的多個對象。然後使用單獨的字符串創建一個添加到數組列表中的新對象。讀取文件時使用分隔符

Amadeus,Drama,160 Mins.,1984,14.83 
As Good As It Gets,Drama,139 Mins.,1998,11.3 
Batman,Action,126 Mins.,1989,10.15 
Billy Elliot,Drama,111 Mins.,2001,10.23 
Blade Runner,Science Fiction,117 Mins.,1982,11.98 
Shadowlands,Drama,133 Mins.,1993,9.89 
Shrek,Animation,93 Mins,2001,15.99 
Snatch,Action,103 Mins,2001,20.67 
The Lord of the Rings,Fantasy,178 Mins,2001,25.87 

我用掃描器讀取該文件,但我得到一個沒有線發現錯誤,整個文件被存儲到一個字符串:

Scanner read = new Scanner (new File("datafile.txt")); 
read.useDelimiter(","); 
String title, category, runningTime, year, price; 

while (read.hasNext()) 
{ 
    title = read.nextLine(); 
    category = read.nextLine(); 
    runningTime = read.nextLine(); 
    year = read.nextLine(); 
    price = read.nextLine(); 
    System.out.println(title + " " + category + " " + runningTime + " " + 
         year + " " + price + "\n"); // just for debugging 
} 
read.close(); 
+1

使用'read.next()'而不是'nextLine()'。 –

回答

0

的一個問題是:

while(read.hasNext()) 
    { 
     title = read.nextLine(); 
     category = read.nextLine(); 
     runningTime = read.nextLine(); 

hasNext() 

如果此掃描器在其輸入中有另一個標記,則返回true。不是整條線。您需要使用hasNextLine()

您正在執行nextLine()三次。我認爲你需要做的是,閱讀行和拆分行。

2

你應該在哪裏你正在使用nextLine();

使用next();看一看教程:不是讀

try { 
    s = new Scanner(new BufferedReader(new FileReader("xanadu.txt"))); 

    while (s.hasNext()) { 
    System.out.println(s.next()); 
} 
3

我想你想打電話.next()它返回一個字符串,而不是.nextLine()。您的.nextLine()呼叫正移過當前線路。

Scanner read = new Scanner (new File("datafile.txt")); 
    read.useDelimiter(","); 
    String title, category, runningTime, year, price; 

    while(read.hasNext()) 
    { 
     title = read.next(); 
     category = read.next(); 
     runningTime = read.next(); 
     year = read.next(); 
     price = read.next(); 
    System.out.println(title + " " + category + " " + runningTime + " " + year + " " + price + "\n"); //just for debugging 
    } 
    read.close(); 
相關問題