2013-01-09 33 views
7

Ho poca esperienza nell'utilizzo dei delimitatori e ho bisogno di leggere un file di testo che memorizza diversi oggetti i cui dati sono memorizzati in singole righe separate da virgole (","). Le stringhe separate vengono quindi utilizzate per creare un nuovo oggetto che viene aggiunto a un arraylist.Utilizzo del delimitatore durante la lettura di un file

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 

Sto usando scanner per leggere il file, però ho un nessuna linea trovato errore e l'intero file viene memorizzato in una stringa:

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

usare 'read.next()' invece di 'nextLine()'. –

risposta

0

Un problema è:

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

hasNext() 

Restituisce vero se questo scanner ha un altro token nel suo input. Non tutta la linea. È necessario utilizzare hasNextLine()

Stai facendo nextLine() tre volte. Penso che quello che devi fare è leggere la linea e dividere la linea.

1

È anche possibile utilizzare una funzione String.split() per convertire la stringa in una matrice di stringhe, quindi scorrere su ciascuna di esse per i valori.

How to convert comma-separated String to ArrayList? vedere questo per ulteriori dettagli.

12

Usa read.next() invece di leggere .nextLine()

title = read.next(); 
    category = read.next(); 
    runningTime = read.next(); 
    year = read.next(); 
    price = read.next(); 
3

Penso che si desideri chiamare .next() che restituisce una stringa anziché .nextLine(). La tua chiamata .nextLine() si sta spostando oltre la riga corrente.

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(); 
Problemi correlati