[Source Code]文件输入输出练习

要求把input.txt的内容读出,输入到文件output.txt中,并且按照分数的降序排列记录。输出文件中,名字长度为10个字节,不足的右补空格;性别长度为2个字节,不足的右补空格;成绩长度为6个字节,不足的左补0

 

文件input.txt内容如下:

Wanglq|M|68.5

Lili|F|98

Wang|M|75

Aaron|M|98

Wang|F|50

 

输出格式如下:

Aaron     |M |000098

Lili      |F |000098

Wang      |M |000075

Wanglq    |M |0068.5

Wang      |F |000050

 

=============== 第一种: 在一个类中解决问题 ====================

package com.mycompany.datatransfer;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;

public class DataTransfer {
 private static final int name_size = 10;

 private static final int sex_size = 2;

 private static final int score_size = 6;

 private static final byte space = ' ';

 private List inrecords = new ArrayList();

 private TreeMap sortedrecs = new TreeMap();

 public void transferData(File src, File target) {
  try {
   inFile(src);

   outFile(target);
  } catch (IOException e) {
   String msg = e.getMessage();
   if (msg.equals("filenotfound")) {
    System.out.println("Can not find the specified file: "
      + src.toString());
   }
   if (msg.equals("input err")) {
    System.out.println("File Reading Error.");
   }
   if (msg.equals("output err")) {
    System.out.println("File Output Error");
   }
  }
 }

 private void inFile(File src) throws IOException {
  BufferedReader buffer = null;

  try {
   buffer = new BufferedReader(new FileReader(src));

   String line;
   while ((line = buffer.readLine()) != null) {
    inrecords.add(line);
   }
  } catch (FileNotFoundException e) {
   // e.printStackTrace();
   throw new FileNotFoundException("filenotfound");
  } catch (IOException e) {
   // e.printStackTrace();
   throw new IOException("input err");
  }
 }

 private void outFile(File target) throws IOException {

  if (inrecords.isEmpty()) {
   return;
  }

  Iterator it = inrecords.iterator();
  while (it.hasNext()) {
   formRecord((String) it.next(),true);
  }

  BufferedWriter out = null;
  try {
   out = new BufferedWriter(new FileWriter(target));

   List keys = new ArrayList(sortedrecs.keySet());
   Collections.sort(keys);
   Collections.reverse(keys);
   
   Iterator it1=keys.iterator();
   List aList;
   while (it1.hasNext()) {
    aList = (List) sortedrecs.get(it1.next());
    Iterator it2= aList.iterator();
    while (it2.hasNext()) {
     Object obj = it2.next();
     System.out.println(obj.toString());
//     out.write(obj.toString());
//     out.newLine();
    }
   }
   
out.flush();
  } catch (IOException e) {
   throw new IOException("output err");
  } finally {
   if (out != null) {
    out.close();
   }

  }
 }

 private void formRecord(String in,boolean dummy){
  StringBuffer sb = new StringBuffer();
  String[] items;
  items = in.split("//|");
  
  sb.append(new String(formItem(items[0].trim().getBytes(),name_size)));
  sb.append(new String(formItem(items[1].trim().getBytes(),sex_size)));
  sb.append(new String(formItem(items[2].trim().getBytes(),score_size)));
  
  BigDecimal key = new BigDecimal(items[2]);
  List aList = (List) sortedrecs.get(key);
  if (aList == null) {
   aList = new ArrayList();
   aList.add(sb.toString());
   sortedrecs.put(key, aList);
  } else {
   aList.add(sb.toString());
   sortedrecs.put(key, aList);
  }
 }
 private void formRecord(String in) {
  StringBuffer ret = new StringBuffer();
  byte[] b;

  b = formItem(in.substring(0, in.indexOf("|")).trim().getBytes(),
    name_size);
  ret.append(new String(b, 0, 10));

  b = formItem(in.substring(in.indexOf("|") + 1, in.lastIndexOf("|"))
    .trim().getBytes(), sex_size);
  ret.append(new String(b, 0, 2));

  b = formItem(in.substring(in.lastIndexOf("|") + 1).trim().getBytes(),
    score_size);
  String score = new String(b, 0, 6);
  ret.append(score);
  BigDecimal key = new BigDecimal(score);
  List aList = (List) sortedrecs.get(key);
  if (aList == null) {
   aList = new ArrayList();
   aList.add(new String(ret));
   sortedrecs.put(key, aList);
  } else {
   aList.add(new String(ret));
   sortedrecs.put(key, aList);
  }
 }

 private byte[] formItem(byte[] bytes, int length) {
  byte[] b = new byte[length];

  switch (length) {
  case score_size:
   for (int i = length - 1, j = bytes.length - 1; i >= 0; i--, j--) {
    if (j < 0) {
     b[i] = '0';
    } else {
     b[i] = bytes[j];
    }
   }
   break;

  default:
   for (int i = 0; i < b.length; i++) {
    if (i < bytes.length) {
     b[i] = bytes[i];
    } else {
     b[i] = space;
    }
   }
   break;
  }
  return b;
 }

 public static void main(String[] args) {
  DataTransfer t = new DataTransfer();
  t.transferData(new File("F://input.txt"), new File("F://output.txt"));
 }

}

==================== 第一种,用到较多的 java.util 中的类 ================================

================== 第二种: 2个类 ===================================

package com.mycompany.datatransfer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class DataTrans {
 private List reclist = new ArrayList();

 public void transData(File src, File target) {
  inFile(src);
  outFile(target);
 }

 private void outFile(File target) {
  Collections.sort(reclist);

  Iterator it = reclist.iterator();
  while (it.hasNext()) {
   System.out.println(it.next());
  }
 }

 private void inFile(File src) {
  BufferedReader buffer = null;
  try {
   buffer = new BufferedReader(new FileReader(src));
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }

  String line;
  String items[];
  try {
   while ((line = buffer.readLine()) != null) {
    Record rec = new Record();
    items = line.split("//|");
    rec.setName(items[0]);
    rec.setSex(items[1]);
    rec.setScore(Double.parseDouble(items[2]));

    reclist.add(rec);
   }
  } catch (IOException e) {
   e.printStackTrace();
  }

 }

 public static void main(String[] args) {
  DataTrans test = new DataTrans();
  test.transData(new File("F://input.txt"), new File(""));
 }

}

package com.mycompany.datatransfer;

public class Record implements Comparable {
 private static final String space = " ";
 
 private String name;

 private String sex;

 private double score;

 public String getName() {
  int nlen = name.length();
  StringBuffer sb = new StringBuffer(name);
  if (nlen<10) {
   for (int i = 0; i < 10-nlen; i++) {
    sb.append(space);
   }
   name = sb.toString();
  }else if (name.length()>10) {
   name = name.substring(0,10);
  }
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getScore() {
  String score = String.valueOf(this.score);
  int spaces = 6-score.length();
  
  if (score.substring(score.length()-1).equals("0")) {
   score = score.substring(0,2);
   spaces += 2;
  }
  
  StringBuffer ret = new StringBuffer();
  for (int i = 0; i < spaces; i++) {
   ret.append("0");
  }
  ret.append(score);

  return ret.toString();
 }

 public void setScore(double score) {
  this.score = score;
 }

 public String getSex() {
  return sex + space;
 }

 public void setSex(String sex) {
  this.sex = sex;
 }

 public String toString() {
  StringBuffer ret = new StringBuffer();
  ret.append(getName());
  ret.append(getSex());
  ret.append(getScore());
  
  return ret.toString();
 }

 public int compareTo(Object recv) {
  double recv_score = ((Record) recv).score;
  return (score < recv_score ? 1 : (score == recv_score ? 0 : -1));
 }

}

================= 第二种,借鉴同事的做法。有点面向对象的意思。 ^_^ ========

 

 

你可能感兴趣的:(list,String,File,null,iterator,import)