Java BufferedInputStream未读取文件

Java BufferedInputStream未读取文件,java,Java,需要你们的帮助。我遇到的问题是我的代码中。当我使用RandomAccessFile时,我在写入或读取文件方面没有任何问题。但是如果我尝试将ObjectInputStream与BufferedInputStream一起使用,第一个对象无法完全读取该文件。 下面是我通过流或随机访问文件读写两种不同方式的代码 public static final String FNAME1 = "1.dat"; public static final String FNAME2 = "2.dat"; final s

需要你们的帮助。我遇到的问题是我的代码中。当我使用RandomAccessFile时,我在写入或读取文件方面没有任何问题。但是如果我尝试将ObjectInputStream与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; 

                }
            }
        }

    }

}

}好吧,我知道我可以这样写

    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));

        }
    }
}

但是如何将inputstream转换为RandomAccessFile?

代码太多了。请阅读:。你还应该读到:我问了一个具体的问题。所有这些代码只是为了让所有的图片广告像其他人一样做我的作业,请-这是一个新问题吗?如果是,请再次单击右上角的“提问”,并提问。您可以解释为什么要混合使用RandomAccessFile和ObjectInputStream.Solved.So,因此不再需要帮助。谢谢