JAVA如何读取TXT文件中的数据并存入arraylist中

2024-11-19 08:32:31
推荐回答(1个)
回答1:

文件放在与生成的class文雀升兆件的顷租相同目录

File filename = new File("file.txt");
InputStreamReader reader = null;
try {
reader = new InputStreamReader( new FileInputStream(filename));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(reader);
String line ="";
Integer max = null;
Integer min = null;
ArrayList a = new ArrayList();
try {
while ((line =br.readLine()) != null) {
Scanner sca=new Scanner(line.trim());
while(sca.hasNextInt()){
a.add(sca.nextInt());
}
}
} catch (IOException e) {

e.printStackTrace();
}
br.close();
Collections.sort(a);

try {

File writename = new File("ppp.txt");
BufferedWriter out;

out = new BufferedWriter(new FileWriter(writename));

out.write("The maximun is "笑册+ a.get(a.size()-1)+ " and the minium is "+ a.get(0));
out.flush();
out.close();

} catch (IOException e) {

e.printStackTrace();

}
System.out.print("The maximun is "+ a.get(a.size()-1)+ " and the minium is "+ a.get(0));