2012-04-27 5 views
0

Это класс, который я только что написал. Ранее он фактически создал файл в другом приложении. Но почему-то это не работает. Это не создает новый файл, и я получаю эту ошибку:Почему мой код не создает новый файл?

package hostelmanagement; 

/** 
* 
* @author princess 
*/ 
/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 

import java.io.Externalizable; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.ObjectInput; 
import java.io.ObjectInputStream; 
import java.io.ObjectOutput; 
import java.io.ObjectOutputStream; 
import java.io.Serializable; 
import java.util.Date; 
import java.util.HashSet; 
import java.util.Set; 
import javax.swing.JOptionPane; 

/** 
* 
* @author princess 
*/ 
public class Student implements Serializable, Externalizable { 

public static Set<Student> listOfStudents = new HashSet<Student>();  
public static File oFile = new File("Student.dat"); 


//Data Members 
private String studentID; 
private String name; 
private Date dateOfReg; 

//Constructor 
Student(String number,String name) 
{ 
this.studentID = number; 
this.name = name; 
dateOfReg = new Date(); 
} 


public String getName() 
{ 
return name; 
} 

public String getStudentID() 
{ 
return studentID; 
} 

public Date getDateOfReg() 
{ 
return dateOfReg; 
} 

public void register() throws FileNotFoundException, IOException, ClassNotFoundException  
{  

HashSet<Student> sss = Student.getListOfStudents(); 
sss.add(this); 
FileOutputStream OFileStream = new FileOutputStream(oFile);  
ObjectOutputStream ObjectOFileStream = new ObjectOutputStream(OFileStream);  
ObjectOFileStream.writeObject(sss); 
ObjectOFileStream.close();  
} 

public static HashSet<Student> getListOfStudents() throws FileNotFoundException, IOException, ClassNotFoundException 
{ 
HashSet ss; 
File iFile = new File("Student.dat"); 
FileInputStream IFileStream = new FileInputStream(iFile); 
ObjectInputStream ObjectIFileStream = new ObjectInputStream(IFileStream); 
ss = (HashSet<Student>) ObjectIFileStream.readObject(); 
ObjectIFileStream.close(); 
return (HashSet<Student>) ss; 
} 

public static void printListOfStudents() throws FileNotFoundException, IOException, ClassNotFoundException 
{ 
HashSet<Student> sa = Student.getListOfStudents(); 
for (Student x : sa) 
{System.out.println(x.toString());} 
} 


public static Student getStudentByID(String aNumber) throws FileNotFoundException, IOException, ClassNotFoundException 
{ 
HashSet<Student> currentListOfStudents = Student.getListOfStudents();  
Student result = null; 
for (Student x : currentListOfStudents) 
    { 
if (x.getStudentID().equalsIgnoreCase(aNumber)) 
     { result = x; 
      break; 
     } 
    } 
     if (result == null) 
    { 
     JOptionPane.showMessageDialog(null, "Student not found"); 
    } 
    return result; 
} 



    @Override 
public String toString() 
{ 
// include the code to retrieve assigned apartment  
return "Name: " + name +" StudentID: "+ studentID + " Registered On: " + dateOfReg; 
} 


    @Override 
public boolean equals(Object another) 
{ 
Student stud = (Student)another; 
return this.name.equals(stud.name)&& this.studentID.equals(stud.studentID); 
} 

    @Override 
public int hashCode() 
{ 
int hash = name.hashCode(); 
return hash; 

} 

    @Override 
    public void writeExternal(ObjectOutput out) throws IOException { 
     throw new UnsupportedOperationException("Not supported yet."); 
    } 

    @Override 
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { 
     throw new UnsupportedOperationException("Not supported yet."); 
    } 
} 

Ошибка:

run: 
Test 1 
Apr 27, 2012 10:19:30 AM hostelmanagement.HostelManagement main 
SEVERE: null 
java.io.FileNotFoundException: Student.dat (The system cannot find the file specified) 
    at java.io.FileInputStream.open(Native Method) 
    at java.io.FileInputStream.<init>(FileInputStream.java:106) 
    at hostelmanagement.Student.getListOfStudents(Student.java:86) 
    at hostelmanagement.Student.register(Student.java:74) 
    at hostelmanagement.HostelManagement.main(HostelManagement.java:34) 
Exception in thread "main" java.io.FileNotFoundException: Student.dat (The system cannot find the file specified) 
    at java.io.FileInputStream.open(Native Method) 
    at java.io.FileInputStream.<init>(FileInputStream.java:106) 
    at hostelmanagement.Student.getListOfStudents(Student.java:86) 
    at hostelmanagement.HostelManagement.main(HostelManagement.java:46) 
Java Result: 1 
BUILD SUCCESSFUL (total time: 0 seconds) 

Где проблема?

ответ

2

Вы ошиблись, значит, вы пытаетесь прочесть файл, которого нет. Он будет создавать новые файлы только при попытке написать им.

Что я буду делать, так это следующее.

public static Set<Student> getListOfStudents() throws IOException, ClassNotFoundException { 
    File studentFile = new File("Student.dat"); 
    FileInputStream in = null; 
    try { 
     in = new FileInputStream(studentFile); 
     ObjectInputStream oos = new ObjectInputStream(in); 
     retyurn (Set<Student>) oos.readObject(); 
    } catch(FileNotFoundException noStudents) { 
     return new HashSet<Student>(); 
    } finally { 
     if (in != null) 
      try { 
       in.close(); 
      } catch(IOException ignored) {} 
    } 
} 
+0

Спасибо, сработало !! Ты спас мой день! – Sasha

3

Учитывая, что вы не предоставляете свою основную логику, я предполагаю, что вы вызываете getListStudents() (чтение файла) перед вызовом register() (ввод файла). Не удивительно, что он этого не находит.

Проблема заключается в том, что ваша программа пытается прочитать файл, который все еще не существует, а не то, что он не смог его создать. Пожалуйста, внимательно прочитайте ваши стеки.

0

Проблема может быть в том, что файл, который вы загружаете в getListOfStudents(), и register() методы могут отсутствовать в указанном месте.

Смежные вопросы