2016-11-29 166 views
-2

需要你的帮助guys.The问题是我的代码。虽然我使用RandomAccessFile我没有任何问题在写或阅读文件。但如果我想使用ObjectInputStream与BufferedInputStream文件不能完全读取(只有第一个对象)。 这里是我的2种不同的阅读方式代码,并通过写码流或RandomAccessFile的Java BufferedInputStream不能读取文件

public static final String FNAME1 = "1.dat"; 
public static final String FNAME2 = "2.dat"; 
final static int ID_SIZE = 10; 
final static int NAME_SIZE = 20; 
final static int GRADE_SIZE = 5; 
final static int RECORD_SIZE = (ID_SIZE + NAME_SIZE + GRADE_SIZE) * 2; // *2 because of the UNI-CODE. 
private static Scanner s = new Scanner(System.in); 

public static void main(String[] args){ 
    int studNum; 
    System.out.println("Please enter how many students: "); 
    studNum=s.nextInt(); 
    Student<?>[] a = new Student[studNum]; 
    try{ 
    createArrary(a,studNum); 
    save(a,FNAME1); 
    System.out.println("2.dat saved successfully!! \n"); 
    fileCopy(FNAME1,FNAME2); 
    System.out.println("The Students in file: "); 
    read(FNAME2); 
    bubbleSort(FNAME1); 
    fileCopy(FNAME1,FNAME2); 
    System.out.println("2.dat after sorting:"); 
    read(FNAME2); 

    }catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

/**Creates array of Students.*/ 
public static Student<?>[] createArrary(Student<?>[] a,int studNum) { 
    String input=""; 
    for(int i = 0; i < studNum; i++) { 
     System.out.println("Student # "+(i+1)+":"); 
     System.out.print("\nPlease enter the student's id: "); 
     int id = s.nextInt(); 
     System.out.print("\nPlease enter Student's name : "); 
     s.nextLine(); 
     String name = s.nextLine(); 
     System.out.print("\nPlease enter Student's grade "); 
     input=s.nextLine(); 
     if(isInteger(input)){ 
      a[i]=new Student<>(id, name,Integer.parseInt(input)); 
     }else{ 
      a[i]=new Student<>(id,name,input); 
     } 
    } 
    return a; 
} 

/**Check if string has integer num.*/ 
public static boolean isInteger(String s) { 
    try { 
     Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
     return false; 
    } catch(NullPointerException e) { 
     return false; 
    } 
    return true; 
} 

/**Save Student array to the file.*/ 
public static void save(Student<?>[] a,String fileName) throws FileNotFoundException, IOException { 
    try (RandomAccessFile f = new RandomAccessFile(fileName, "rw")) { 
     f.setLength(0); 
     for (Student<?> p : a) { 
      writeFixedLengthString(String.valueOf(p.getId()),ID_SIZE,f); 
      writeFixedLengthString(p.getFullName(),NAME_SIZE,f); 
      writeFixedLengthString(String.valueOf(p.getGrade()),GRADE_SIZE,f); 
     } 
    } 
} 

public static void save(Student<?>[] a,String fileName) throws FileNotFoundException, IOException { 
    try(ObjectOutputStream o = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)))){ 
     for(Student<?> p : a){ 
      writeFixedLengthString(String.valueOf(p.getId()),ID_SIZE,o); 
      writeFixedLengthString(p.getFullName(),NAME_SIZE,o); 
      writeFixedLengthString(String.valueOf(p.getGrade()),GRADE_SIZE,o); 
     } 
    } 
} 

/**Read Students from file.*/ 
public static void read(String fileName) throws FileNotFoundException, IOException,NumberFormatException { 
    try (RandomAccessFile f = new RandomAccessFile(fileName, "r")) { 
     while (f.getFilePointer() < f.length()) { 
      int id=Integer.parseInt(readFixedLengthString(ID_SIZE,f)); 
      String name=readFixedLengthString(NAME_SIZE,f); 
      String grade=readFixedLengthString(GRADE_SIZE,f); 
      System.out.println(new Student<>(id, name,grade)); 
     } 
    } 
} 
public static void read(String fileName) throws FileNotFoundException, IOException,NumberFormatException { 
    BufferedInputStream f; 
    try(ObjectInputStream i = new ObjectInputStream(f = new BufferedInputStream(new FileInputStream(fileName)))){ 
     while (f.available() > 0) { 
      int id=Integer.parseInt((readFixedLengthString(ID_SIZE,i))); 
      String name=readFixedLengthString(NAME_SIZE,i); 
      String grade=readFixedLengthString(GRADE_SIZE,i); 
      System.out.println(new Student<>(id, name,grade)); 

     } 
    } 
} 

/** Write fixed number of characters to a DataOutput stream */ 
public static void writeFixedLengthString(String s, int size, 
      DataOutput out) throws IOException 
    { char[] chars = new char[size]; 
    s.getChars(0, Math.min(s.length(), size), chars, 0); 
    for (int i = s.length(); i < size; i++) 
     chars[i] = ' '; 
    out.writeChars(new String(chars)); 
    } 

/** Read fixed number of characters from a DataInput stream */ 
public static String readFixedLengthString(int size, DataInput in) 
     throws IOException 
    { char[] chars = new char[size]; 
    for (int i = 0; i < size; i++) 
     chars[i] = in.readChar(); 
    return new String(chars).replaceAll(" ", ""); 
    } 

/** Copying source file to destination file */ 
public static void fileCopy(String fileSource,String fileDest) throws FileNotFoundException,IOException{ 
    try(BufferedInputStream input=new BufferedInputStream(new FileInputStream(fileSource));BufferedOutputStream output =new BufferedOutputStream(new FileOutputStream(fileDest));){ 
     int r; 
     while ((r = input.read()) != -1) 
     { output.write(r); 
     } 
    } 
} 

/** Read Students from file and returns Object */ 
public static <T> Student<?> readSort(RandomAccessFile f) throws FileNotFoundException, IOException,NumberFormatException { 
    int id=Integer.parseInt(readFixedLengthString(ID_SIZE,f)); 
     String name=readFixedLengthString(NAME_SIZE,f); 
      String grade=readFixedLengthString(GRADE_SIZE,f); 
     return new Student<>(id, name,grade); 
    } 

/** Receive Student Objects and Save them to file */ 
public static <T> void saveSort(Student<T> stud,RandomAccessFile f) throws FileNotFoundException, IOException { 
      writeFixedLengthString(String.valueOf(stud.getId()),ID_SIZE,f); 
      writeFixedLengthString(stud.getFullName(),NAME_SIZE,f); 
      writeFixedLengthString(String.valueOf(stud.getGrade()),GRADE_SIZE,f); 

} 

/** Bubble Sort of Student's grades */ 
@SuppressWarnings("unchecked") 
public static <T> void bubbleSort(String file) throws FileNotFoundException, IOException { 
    try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) { 
     boolean needNextPass = true; 
     for (int k = 1; k < raf.length()/RECORD_SIZE && needNextPass; k++) { 

      needNextPass = false; 
      for (int i = 0; i < (raf.length()/RECORD_SIZE) - k; i++) { 

       raf.seek(RECORD_SIZE * i); 
       long tmpPrev = raf.getFilePointer(); 
       Student<T> prevStud = (Student<T>) readSort(raf); 
       long tmpNext = raf.getFilePointer(); 
       Student<T> nextStud = (Student<T>) readSort(raf); 


       if(isInteger((String) prevStud.getGrade())&&isInteger((String) nextStud.getGrade())){ 
        if(Integer.parseInt((String) prevStud.getGrade())>Integer.parseInt((String) nextStud.getGrade())){ 
         Student<T> temp=prevStud; 
         prevStud = nextStud; 
         nextStud = temp; 
         raf.seek(tmpPrev); 
         saveSort(prevStud, raf); 
         raf.seek(tmpNext); 
         saveSort(nextStud, raf); 

         needNextPass = true; 
        } 

       }else if(String.valueOf(prevStud.getGrade()) 
         .compareTo(String.valueOf(nextStud.getGrade())) > 0 &&!isInteger((String) prevStud.getGrade())&&!isInteger((String) nextStud.getGrade())){ 
        Student<T> temp=prevStud; 
        prevStud = nextStud; 
        nextStud = temp; 
        raf.seek(tmpPrev); 
        saveSort(prevStud, raf); 
        raf.seek(tmpNext); 
        saveSort(nextStud, raf); 

        needNextPass = true; 

       }else if(isInteger((String) prevStud.getGrade())&&!isInteger((String) nextStud.getGrade())||!isInteger((String) prevStud.getGrade())&&isInteger((String) nextStud.getGrade())&&String.valueOf(prevStud.getGrade()) 
         .compareTo(String.valueOf(nextStud.getGrade())) < 0){ 
        Student<T> temp=prevStud; 
        prevStud = nextStud; 
        nextStud = temp; 
        raf.seek(tmpPrev); 
        saveSort(prevStud, raf); 
        raf.seek(tmpNext); 
        saveSort(nextStud, raf); 

        needNextPass = true; 

       } 
      } 
     } 

    } 

} 

}

+0

代码太多。请阅读:[如何创建**最小**,完整和可验证示例](http://stackoverflow.com/help/mcve)。您还应该阅读:[我如何问一个好问题?](http://stackoverflow.com/help/how-to-ask) – Andreas

+0

我问具体问题。所有这些代码只是为了给所有图片 –

回答

0

确定我明白我可以这样写。

public static void read(String fileName) throws FileNotFoundException, IOException,NumberFormatException { 
    try(ObjectInputStream i = new ObjectInputStream(new BufferedInputStream(new FileInputStream(fileName)))){ 
     while (i.available()>0) { 
      int id=Integer.parseInt((readFixedLengthString(ID_SIZE,i))); 
      String name=readFixedLengthString(NAME_SIZE,i); 
      String grade=readFixedLengthString(GRADE_SIZE,i); 
      System.out.println(new Student<>(id, name,grade)); 

     } 
    } 
} 

但我怎么能将输入流翻译为RandomAccessFile?

+0

这是一个新问题吗?如果是这样,请再次点击右上角的“提问”,然后提问。你可能会解释为什么*你想混合使用RandomAccessFile和ObjectInputStream。 – Andreas

+0

解决了。所以不需要帮助了。谢谢 –