I am trying to read an object via ObjectInputStream. However I retrieve the following stacktrace with an EOFException:
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2325)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2794)
at
java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:801)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at student.operations.StudentOperations.addStudentDetails(StudentOperations.java:46)
at student.
My code is the following:
FileInputStream fi = new FileInputStream(file.getPath());
ObjIn = new ObjectInputStream(fi);
FileOutputStream fo = new FileOutputStream(file.getPath());
Objout = new ObjectOutputStream(fo);
//bo = new BufferedOutputStream(Objout);
//bi = new BufferedInputStream(ObjIn);
System.out.println("Enter the number of students to add");
number = in.nextInt();
System.out.println("Enter Student roll number:");
int rollno = in.nextInt();
try {
HashMap<Integer, StudentModel> hs = (HashMap<Integer, StudentModel>) ObjIn
.readObject();
if (hs.containsKey(rollno)) {
System.out.println("Duplicate values are not allowed ");
} else {
for (counter = 0; counter < number; counter++) {
System.out.println("Enter Student name:");
String name = in.next();
System.out.println("Enter Student's Father name:");
String fname = in.next();
System.out.println("Enter Gender:");
String gender = in.next();
System.out.println("Enter Date of birth:");
String date = in.next();
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy");
Date dateObj = null;
try {
dateObj = dateFormat.parse(date);
} catch (ParseException e) {
System.out.println(e);
}
Calendar birthday = Calendar.getInstance();
birthday.setTimeInMillis(dateObj.getTime());
Calendar current = Calendar.getInstance();
long currentTime = System.currentTimeMillis();
current.setTimeInMillis(currentTime);
int age = current.get(Calendar.YEAR)
- birthday.get(Calendar.YEAR);
System.out.println("Enter the AddressLine1:");
String address1 = in.next();
in.nextLine();
System.out.println("Enter the AddressLine2:");
String address2 = in.next();
in.nextLine();
System.out.println("Enter the city");
String city = in.next();
in.nextLine();
System.out.println("Enter the state");
String state = in.next();
in.nextLine();
System.out.println("Enter the country:");
String country = in.next();
in.nextLine();
System.out.println("Enter the Zipcode");
int code = in.nextInt();
in.nextLine();
StudentUtill.student.put(rollno, new StudentModel(name,
fname, rollno, age, gender, dateObj, address1,
address2, city, state, country, code));
Objout.writeObject(StudentUtill.student.toString());
Objout.flush();
}// for loop ends here
tester.StudentTester.main(StudentTester.java:30)
You're trying to read objects from an empty file. Look at the stack trace. End of file trying to read the header. There isn't even a header in the file, let alone an object. It's empty.
Don't create a FileOutputStream until you have something to write to it, and don't forget to close it immediately afterwards.
You're also incorrectly converting the map to a String before writing it to the file, but you haven't yet got to the point where that's a problem.
Related
I'm using NetBeans 16 and I'm trying to add the ability to edit a record from a text file I have saved separated by commas.
Ive tried this code here and I don't seem to get any errors (except the one produced as a result of the try catch) but I have no idea why this doesn't seem to work when I try to overwrite a record which I have selected ive tried everything I can think of I'm pretty new to coding so forgive me if there's some obvious error but I have no idea why this doesn't work my text file has 5 entries in a row if that helps but yeah any help is greatly appreciated
public class EditRecords {
private static Scanner x;
public static void main(String[]args)
{
String filepath = "VehicleInforUpd.txt";
System.out.println("Enter Registration of Entry You Wish To Edit");
Scanner scanner = new Scanner(System.in);
String editTerm = scanner.nextLine();
System.out.println("Enter new Registration: ");
String newReg = scanner.nextLine();
System.out.println("Enter new Make: ");
String newMake = scanner.nextLine();
System.out.println("Enter New Model: ");
String newModel = scanner.nextLine();
System.out.println("Enter New Year: ");
String newYear = scanner.nextLine();
System.out.println("Enter New Comments: ");
String newComment = scanner.nextLine();
editRecord(filepath,editTerm,newReg,newMake,newModel,newYear,newComment);
}
public static void editRecord(String filepath,String editTerm,String newReg,String newMake,String newModel, String newYear, String newComment)
{
String tempFile = "temp.txt";
File oldFile = new File(filepath);
File newFile = new File(tempFile);
String reg = ""; String make = ""; String model = ""; String year = ""; String comment = "";
try
{
FileWriter fw = new FileWriter(tempFile,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
while(x.hasNext())
{
reg = x.next();
make = x.next();
model = x.next();
year = x.next();
comment = x.next();
if(reg.equals(editTerm))
{
pw.println(newReg+","+newMake+","+newModel+","+ newYear+","+newComment);
}
else
{
pw.println(reg+","+make+","+model+","+year+","+comment);
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File(filepath);
newFile.renameTo(dump);
JOptionPane.showMessageDialog(null, "Changes Succesfully Saved");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
The Print stack trace results but im not sure what would cause the NullPointerException im getting
java.lang.NullPointerException
at com.mycompany.anprsystems.EditRecords.editRecord(EditRecords.java:70)
at com.mycompany.anprsystems.EditRecords.main(EditRecords.java:52)
public void populateFromFile(String filename)
{
try
{
Scanner sc = new Scanner(new File(filename));
//variables
String firstName;
String lastName;
String emailAddress;
String startYear;
String startMonth;
String clubName;
Member tmp;
//skip first line
sc.nextLine();
sc.useDelimiter(";");
sc.skip(
while (sc.hasNext())
{
sc.next();
firstName = sc.next();
lastName = sc.next();
emailAddress = sc.next();
startYear = sc.next();
int year = Integer.parseInt(startYear);
startMonth = sc.next();
int month = Integer.parseInt(startMonth);
clubName = sc.next();
tmp = new Member(firstName,lastName,emailAddress,month,year);
if(clubName == name)
{
addMember(tmp);
}
}
sc.close();
}
catch(Exception e){
System.out.println(e);
};
}
I'm trying to find a way how I only can add the 'Members' who are from the correct club. But when I am trying to put an if statement in the while loop the program runs forever. Do you have any other idea how I could do this?
Here's an example I created based on your problem. This should solve your problem.
String str = "x;a1;b1;c1;d1\ny;a2;b2;c2;d2\nx;a3;b3;c3;d4";
Scanner s = new Scanner(str);
while(s.hasNextLine()){
Scanner s2 = new Scanner(s.nextLine());
s2.useDelimiter(";");
String h = s2.next();
String a = s2.next();
String b = s2.next();
String c = s2.next();
String d = s2.next();
if (h.equals("x")){
System.out.printf("%s|%s|%s|%s\n", a,b,c,d);
}
}
The output is:
a1|b1|c1|d1
a3|b3|c3|d3
I am trying to run this code where it reads a file and sorts the words by the tabs in between the words.
File Example
Area Word Area Word Area 1111 Word
public static void start() throws FileNotFoundException {
// Create Empty address book
AddressBook book = new AddressBook();
Scanner scnr = new Scanner(System.in);
String filename = "contacts.txt";
addContactfromFile(book,filename);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
// Insert contacts FEATURE
System.out.println("------------------------INSERTING CONTACT--------------------------------");
int ans = 0;
System.out.println("Would you like to insert a Contact? 1 or 2");
ans = scnr.nextInt();
scnr.nextLine();
if(ans == 1){
System.out.println("What is the First name");
String f = scnr.nextLine();
System.out.println("What is the Last name");
String l = scnr.nextLine();
System.out.println("What is the Number name");
String n = scnr.nextLine();
System.out.println("What is the Address name");
String a = scnr.nextLine();
System.out.println("What is the City name");
String c = scnr.nextLine();
System.out.println("What is the State name");
String s = scnr.nextLine();
System.out.println("What is the Zip Code name");
int z = scnr.nextInt();
book.insertContact(f,l,n,a,c,s,z);
System.out.println("Contact has been added!");
}else {
System.out.println("Ok");
}
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// search FEATURE
System.out.println("------------------------SEARCHING CONTACT--------------------------------");
addContactfromFile(book, "contacts.txt");
checkSearch(book);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// delete Contact FEATURE
System.out.println("------------------------DELETING CONTACT--------------------------------");
addContactfromFile(book, "contacts.txt");
checkDelete(book);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// Check if address book is empty FEATURE
addContactfromFile(book, "contacts.txt");
System.out.println("Is the Address Book Empty: "+book.isAddressBookEmpty());
System.out.println(book.getNumberOfContacts());
}
public static void checkSearch(AddressBook book) throws FileNotFoundException{
Scanner scnr = new Scanner(System.in);
System.out.println("Who would like to look for?'First name'");
String first = scnr.nextLine();
System.out.println("Who would like to look for?'Last name'");
String last = scnr.nextLine();
try{
Contact c = book.searchContact(first,last);
System.out.println(c.getFirstName()+ " " + c.getAddress().getStreet());
}catch (Exception e){
System.out.println(e);
System.out.println("Contact isnt there");
}
}
public static void checkDelete(AddressBook book) throws FileNotFoundException{
Scanner scnr = new Scanner(System.in);
System.out.println("Enter First Name");
String first = scnr.nextLine();
System.out.println("Enter Last Name");
String last = scnr.nextLine();
try{
book.deleteContact(first,last);
}catch (Exception e){
System.out.println(e);
System.out.println("Didnt work");
}
}
public static void addContactfromFile(AddressBook book, String filename) throws NumberFormatException, FileNotFoundException{
Scanner reader = new Scanner(new File(filename));
while(reader.hasNextLine()) {
String contactString = reader.nextLine();
String[] contactElementStrings = contactString.split("\t");
int zipcode = Integer.parseInt(contactElementStrings[5]);
Address address = new Address(contactElementStrings[2],contactElementStrings[3],contactElementStrings[4],zipcode);
Contact contact = new Contact(contactElementStrings[0],contactElementStrings[1],address,contactElementStrings[6]);
book.insertContact2(contact);
}
}
The Error I receive from this is:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at Helper.addContactfromFile(Helper.java:106)
at Helper.start(Helper.java:16)
at Driver.main(Driver.java:17)
contactElementStrings[5] contains an empty string.
Integer.parseInt(contactElementStrings[5]) is throwing NumberFormatException because an empty string cannot be parsed to an int.
Add a check to see whether contactElementStrings[5] can be parsed to an int.
int zipcode;
if (contactElementStrings.length > 6) {
if (contactElementStrings[5] != null && !contactElementStrings[5].isEmpty()) {
zipcode = Integer.parseInt(contactElementStrings[5]);
}
else {
zipcode = 0;
}
}
EDIT
From your comment, it appears that there are lines that don't contain all the fields that you expect. Hence you also need to check whether the split line contains all the expected parts. I have edited the above code to also check whether the split line contains all the expected parts.
This question already has answers here:
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 3 years ago.
I have a class Test with a static method to take input.
class Test {
public static Student readStudent() throws IOException {
Scanner s = new Scanner(System.in);
System.out.println("Enter first name of student");
String fname = s.nextLine();
System.out.println("Enter middle name of student");
String mname = s.nextLine();
System.out.println("Enter last name of student");
String lname = s.nextLine();
System.out.println("Enter name format(1 for ',' and 2 for ';') ");
int num = s.nextInt();
System.out.println("Enter age of student");
int age = s.nextInt();
s.close();
return new Student(new Name(String.join((num == 1) ? "," : ";", fname,
mname, lname)), age);
}
}
I am able to take the input for one student but once i put it in a for loop i get a java.util.NoSuchElementException: No line found error.
This is my loop
for (int i = 0; i < 10; i++) {
Student s = Test.readStudent();
}
Why am I getting this error? Thanks.
s.close(); closes the current Scanner object, but also all underlying streams, which is System.in in this case. Once your standard input stream is closed, you cannot open it anymore.
So all in all it would be best to close your Scanner after you're sure you won't need it anymore and restructure your code like this:
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
Student s = Test.readStudent(sc);
// do something with your student object here
}
sc.close();
And change your method to
public static Student readStudent(Scanner s) throws IOException {
Scanner s = new Scanner(System.in);
System.out.println("Enter first name of student");
String fname = s.nextLine();
System.out.println("Enter middle name of student");
String mname = s.nextLine();
System.out.println("Enter last name of student");
String lname = s.nextLine();
System.out.println("Enter name format(1 for ',' and 2 for ';') ");
int num = s.nextInt();
s.nextLine(); // Need to consume new line
System.out.println("Enter age of student");
int age = s.nextInt();
s.nextLine(); // Need to consume new line
// no closing here
return new Student(new Name(String.join((num == 1) ? "," : ";", fname,
mname, lname)), age);
}
I'm writing JDBC in Java, my thought is to write a method called userInsertCruise, which can make user input the data, and these data will add a new row into my database table.
Here is my code look like:
public class Insert_Cruise {
public void userInsertCruise(Date sailingDate, Date returnDate,String departurePort,
String shipName, String portOfCalls, String cruiseSerialNumber, int passengerID){
while(true){
System.out.println("Input the sailing date:");
Scanner sc1 = new Scanner(System.in);
sailingDate = java.sql.Date.valueOf(sc1.next());
System.out.println("Input the return date :");
Scanner sc2 = new Scanner(System.in);
returnDate = java.sql.Date.valueOf(sc2.next());
System.out.println("Input the departure port:");
Scanner sc3 = new Scanner(System.in);
departurePort = sc3.next();
System.out.println("Input the ship name");
Scanner sc4 = new Scanner(System.in);
shipName = sc4.next();
System.out.println("Input the ports of calls:");
Scanner sc5 = new Scanner(System.in);
portOfCalls = sc5.next();
System.out.println("Input the cruise serial number:");
Scanner sc6 = new Scanner(System.in);
cruiseSerialNumber = sc5.next();
System.out.println("Input the passenger ID:");
Scanner sc7 = new Scanner(System.in);
passengerID = sc7.nextInt();
System.out.println("Are you finish establish your data? Y/N");
Scanner ans = new Scanner(System.in);
String answer = ans.next();
if(answer != "y"){
break;
}else{
continue;
}
public void insertCruise() throws SQLException
{
String url = ("org.apache.derby.jdbc.ClientDriver");
Connection conn = null;
Statement st = conn.createStatement();
try {
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/mydata");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
try {
st.executeUpdate("INSERT INTO CRUISE ("
+ "SAILING_DATE, RETURN_DATE, DEPARTURE_PORT, SHIP_NAME,
PORTS_OF_CALLS, CRUISE_SERIAL_NUMBER, PASSENGER_ID_NUMBER) "
+ "VALUES (?,?,?,?,?,?,?)");
} catch (SQLIntegrityConstraintViolationException e) {
System.out.println("Record Already exists.");
}
}
Then I want to call the method in main:
Insert_Cruise insert = new Insert_Cruise();
insert.userInsertCruise(sailingDate, returnDate, passward, username, passward, username, 0);
insert.insertCruise();
However, it does not work. Because I have no parameter to input in the userInsertCruise method.
The reason that I don't want to use Scanner in the main method is it would make the main method too long. And I have to make user can insert row in different tables in my database, if I write all the scanner in main, it would be very mess.
Is there any method to fix this problem?