Getting integers from text file and work on array list in java -
i have text file contains:
" have 3 apples , 1 banana.
all people have 4 cars @ least."i want read .txt file , integers it.i strore integer variables in arraylist.
public class dedede { public static void al() throws exception { file f = new file("c:\\users\\sony\\desktop\\456.txt"); try { filereader islem = new filereader(f); char data[] = new char[(int) f.length()]; islem.read(data); string metin = new string(data); arraylist<integer> yapi = new<integer> arraylist(); stringtokenizer s = new stringtokenizer(metin); string dizi[] = new string[s.counttokens()]; int = 0; while (s.hasmoretokens()) { dizi[i] = s.nexttoken(); i++; } (int c = 0; c < dizi.length; c++) { if (integer.parseint(dizi[c]) > 0) { yapi.add(integer.parseint(dizi[c])); } } system.out.println(yapi); } catch (ioexception e) { e.printstacktrace(); } } public static void main(string[] args) throws exception { al(); } }
try this:
static arraylist<integer> al = new arraylist<integer>(); public static void main(string[] args) { try { file file = new file("c:\\users\\sony\\desktop\\456.txt"); bufferedreader in = new bufferedreader(new filereader(file)); string s; while ((s = in.readline()) != null) { findinteger(s); } in.close(); } catch (ioexception e) { system.out.println("file read error: " + e.getmessage()); } system.out.println("integers: " + al); } private static void findinteger(string s){ string [] parts = s.split(" "); (int = 0; < parts.length; i++) { try{ int j = integer.parseint(parts[i]); al.add(j); } catch (exception e){} } }
Comments
Post a Comment