先来说你的问题,,你要实现写入文件是排序的结果,,那么你就应该先排序再写到文件,,而不是你现在这样接受一个写一个,,再说为什么文件里面是乱码,是因为你每次写入文件的时候写了一个字符‘0’,这个写到文件中打开后并不是你想看到的字符串“0”,所以打开是乱码,
帮你简单修改了代码
public static void main(String args[])
{
Scanner scanner=new Scanner(System.in);
try
{
int sum=0;// 总分
RandomAccessFile f=new RandomAccessFile("data.txt","rw");
System.out.print("请输入学生的个数: ");
int n=scanner.nextInt();
int s[]=new int[n];
for(int i=0;i{
System.out.println("请输入第"+(i+1)+"个学生的成绩");
s[i]=scanner.nextInt();
sum+=s[i];
}
System.out.println("总分:"+sum);
Arrays.sort(s);
f.writeBytes(Arrays.toString(s));
f.close();
}
catch(IOException e)
{
System.err.println(e);
e.printStackTrace();
}
}
随机文件(RandomAccessFile)读写的一些方法,如writeInt writeChar 等,这些方法写到文件的数据都是二进制的,比如你writeInt(25),写到文件后打开是不会看到25的,这点一定要注意
public class ScoreFile {
public static void main(String args[]) throws IOException {
int sum = 0;
System.out.println("请输入学生的个数");
int n = new Scanner(System.in).nextInt();
int s[] = new int[n];
for (int i = 0; i < n; i++) {
System.out.println("请输入第" + (i + 1) + "个学生的成绩");
s[i] = new Scanner(System.in).nextInt();
sum += s[i];
}
writeIntoFile(sortScore(s));
}
//数组排序
public static int[] sortScore(int[] score){
int temp = 0;
//大->小
for(int i=0;ifor(int j=i+1;j if(score[j]>score[i]){
temp = score[i];
score[i] = score[j];
score[j] = temp;
}
}
}
return score;
}
//从大到小写入文件
public static void writeIntoFile(int[] score) throws IOException{
RandomAccessFile rf = new RandomAccessFile("d://11.txt", "rw");
//解决乱码
byte buffer[] = new byte [ 1024 ];
for(int i : sortScore(score)){
buffer = String.valueOf(i).getBytes();
rf.write(buffer);
rf.writeBytes("\r\n");
}
rf.close();
}
}