本文提供了一个使用Java实现的文件排序示例。该程序读取名为input.txt的文件,其中每行包含五个数字,对其进行排序,并将排序后的结果写入output.txt文件中。通过此示例,读者可以了解如何使用Java的文件读写API以及字符串操作来完成简单的文件处理任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 package com.qwnbc.sample;
import java.io.*;
import java.util.Properties;

/**
 * @author 张 柏
 * @copyright qwnbc 2009-5-27
 * 有一个input.txt文件
 * 该文件每一行有五个数字
 * 1,1,2,4,2
 * 1,1,2,2,4
 * 1,3,73,189,8
 * 2,4,3,55,9
 * 1,4,12,34,67
 * 1,5,8,9,13
 * 3,5,8,78,55

 *
 * 对这个文件进行排序
 * 输出形式是output.txt
 * 1,1,2,2,4
 * 1,1,2,2,4
 * 1,1,8,73,189
 * 1,4,12,34,67
 * 1,5,8,9,13
 * 2,3,4,9,55
 * 3,5,8,55,78
 */
public class StreamDemo {
 public static void main(String args[]) throws IOException {
  FileReader fr = new FileReader("c://input.txt");
  BufferedReader re = new BufferedReader(fr);
  FileWriter fw = new FileWriter("c://output.txt");
  BufferedWriter bw = new BufferedWriter(fw);
  while (1 == 1) {
   if (re.ready()) {
    String str = re.readLine();
    String[] arrInt = str.split(",");
    for (int i = 0; i < arrInt.length; i++) {
     String temp = null;
     for (int j = 0; j < arrInt.length - i - 1; j++) {
      String s1 = arrInt[j].trim();
      String s2 = arrInt[j + 1].trim();
      if (s1.hashCode() > s2.hashCode()) {
       temp = arrInt[j];
       arrInt[j] = arrInt[j + 1];
       arrInt[j + 1] = temp;
      }
     }
    }
    StringBuffer sb = new StringBuffer();
    for (int k = 0; k < arrInt.length; k++) {
     if (k < arrInt.length - 1) {
      sb.append(arrInt[k] + ",");
     } else
      sb.append(arrInt[k]);
    }
    Properties pp = System.getProperties();
    String newLine = pp.getProperty("line.separator");
    bw.write(sb.toString() + newLine);
   } else
    break;
  }
  fr.close();
  bw.close();
 }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值