我的文本文件包含:
“我有3个苹果和1个香蕉。所有人至少有4辆汽车。”我想读取这个.txt文件并从中获取整数。我将在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 i = 0;
while (s.hasMoreTokens()) {
dizi[i] = s.nextToken();
i++;
}
for (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();
}
}
答案 0 :(得分:2)
试试这个:
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(" ");
for (int i = 0; i < parts.length; i++) {
try{
int j = Integer.parseInt(parts[i]);
al.add(j);
} catch (Exception e){}
}
}