1个回答
展开全部
在c盘新建1.txt 输入若干数字,代码运行后会把排序后的数字存入c盘下的2.txt
java代码:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
BufferedReader br = null;
FileWriter fw = null;
String str = null;
StringBuffer sb = null;
String[] strs = null;
try {
br = new BufferedReader(new FileReader("c:\\1.txt"));
fw = new FileWriter("c:\\2.txt");
sb = new StringBuffer();
while ((str = br.readLine()) != null) {
System.out.println("文件内容: " + str);
strs = str.split(" ");
for (int k = 0; k < strs.length - 1; k++) {
for (int j = k + 1; j < strs.length; j++) { // 升序把<改成>
if (Integer.valueOf(strs[k]) < Integer.valueOf(strs[j])) {
String temp = strs[k];
strs[k] = strs[j];
strs[j] = temp;
}
}
}
for(int k = 0; k < strs.length; k++){
sb.append(strs[k] + " ");
}
fw.write(sb.toString());
fw.flush();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(br != null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fw != null){
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
2.txt存放排序后的数
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询