PDA

View Full Version : [java] Problema con java e file di testo


lil_billy
16-09-2011, 00:59
Buonasera a tutti...
ho un file di testo composto da piu righe ed ogni riga è composta da:
stringa valore_intero stringa
io dovrei fare la somma sei vari valori interi presenti nelle varie righe ma non sò come estrarli :mc:
qualcuno di voi può gentilmente darmi una mano?:D
allego il codice:


import java.io.*;
import java.util.*;

class tl
{
public static void main(String [] args)
{
int somma=0;
String s;
try
{
BufferedReader in=new BufferedReader (new FileReader("testo.txt"));
s=in.readLine();
while(s!=null)
{
StringTokenizer st = new StringTokenizer(s, " ");
System.out.println(s);
if(sc.hasNextInt()) somma=sc.nextInt();
System.out.println("Intero: "+ somma);
s=in.readLine();
}
}
catch(FileNotFoundException e)
{
System.out.println("Errore apertura file testo");
System.out.println(0);
}
catch(IOException e)
{
System.out.println("Errore I/O file");
System.out.println(0);
}

}
}

Floris
16-09-2011, 04:24
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead. Fonte:http://download.oracle.com/javase/6/docs/api/
Quindi dovresti provare ad usare le funzionalità di String invece di StringTokenizer.

Prova questo:

package example;

import java.io.*;

public class Main {

public static void main(String[] args) {

int somma = 0;
File file = new File("Prova.txt");
try{
DataInputStream istream = new DataInputStream(new FileInputStream(file));
byte[] raw_bytes = new byte[(int)file.length()];
istream.read(raw_bytes,0,(int)file.length());
istream.close();
String s = new String(raw_bytes);
String[] tokens = s.split("[ \t\n]");
int i = 1;
while(i<=tokens.length){
somma += Integer.parseInt(tokens[i]);
i += 3;
}
System.out.println(somma);
}catch(Exception e){System.out.println(e.getMessage());System.exit(-1);}

}

}

Come formato di file (Prova.txt) ho usato una cosa del genere:

5 1 come
va 4 100
te 5 11