JAVA如何读取TXT文件中的数据并存入arraylist中
如何将TXT文件中的数字读取出来,然后存入arraylist中并且比较大小,将最大最小值再写回同样的文件中。求大神指导,本人菜鸟一个。最好能写出代码来。跪谢了。数字存储格...
如何将TXT文件中的数字读取出来,然后存入arraylist中并且比较大小,将最大最小值再写回同样的文件中。求大神指导,本人菜鸟一个。最好能写出代码来。跪谢了。
数字存储格式如下图
另外,txt文件应该放在哪个文件夹中呢? 展开
数字存储格式如下图
另外,txt文件应该放在哪个文件夹中呢? 展开
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<Integer> a = new ArrayList<Integer>();
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));
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<Integer> a = new ArrayList<Integer>();
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));
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询