So, I'm trying to read in an Object from a file, and I can't figure out why I'm getting this exception, or how to fix it. Maybe you guys can help me out? I've tried messing around with the way I read the object, but can't get it quite right. Here is my code I'm getting the error on the line that reads listOfEmployeesIn[i] = (Employee) objIn.readObject();:
import java.util.Random;
import java.io.*;
public class ProjectFive{
public static void main(String[] args) throws IOException{
Random rn = new Random();
RandomAccessFile file = new RandomAccessFile("employees.txt", "rw");
FileOutputStream fileOut = new FileOutputStream("employees.txt");
ObjectOutputStream objOut = new ObjectOutputStream(fileOut);
FileInputStream fileIn = new FileInputStream("employees.txt");
ObjectInputStream objIn = new ObjectInputStream(fileIn);
Object x;
long SSN;
float salary;
int age;
float maxSalary = 200000;
float minSalary = 20000;
long SSNRange = 1000000000;
String[] names = {"Matty Villa"};
Employee[] listOfEmployeesOut = new Employee[20];
Employee[] listOfEmployeesIn = new Employee[20];
for(int i=0;i<listOfEmployeesOut.length;i++){
SSN = (long)(rn.nextDouble()*SSNRange);
salary = rn.nextFloat()*(maxSalary - minSalary)+minSalary;
age = rn.nextInt(57)+18;
listOfEmployeesOut[i] = new Employee(SSN, names[i], salary, age);
}
for(int i = 0;i<listOfEmployeesOut.length;i++){
objOut.writeObject(listOfEmployeesOut[i]);
}
for(int i = 0;i<listOfEmployeesIn.length;i++){
listOfEmployeesIn[i] = (Employee) objIn.readObject();
}
file.close();
fileOut.close();
objOut.close();
fileIn.close();
objIn.close();
}
}
class Employee implements Serializable{
public long socialSecurityNumber;
public String fullName;
public float salary;
public int age;
public Employee(long socialSecurityNumber, String fullName, float salary, int age){
this.socialSecurityNumber = socialSecurityNumber;
if(fullName.length() != 50){
fullName = resizeString(fullName);
}
this.fullName = fullName;
this.salary = salary;
this.age = age;
}
private String resizeString(String s){
if(s.length() < 50){
for(int i = s.length(); i<=50; i++){
s += ' ';
}
}else{
s = s.substring(0,50);
}
return s;
}
public String toString(){
String out = "Name: " + fullName + "\nSalary: " + salary + "\nSocial: " + socialSecurityNumber
+ "\nAge: " + age;
return out;
}
}
As per JAVA API for ObjectInputStream, the method readObject throws checked exceptions - IOException, ClassNotFoundException
So either throw this exception from main method:
public static void main(String[] args) throws IOException, ClassNotFoundException
or handle it using try/catch blocks:
try {
listOfEmployeesIn[i] = (Employee) objIn.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Related
I am making a program where user inputs his/her info and it is written in the file in binary form and after that we ask for a name whose info we want to get from the file. In that I take all the inserted objects into a arraylist and then match the name with respective name corresponding to the objects
this is my code
import java.util.*;
import java.io.*;
class MyObjectOutputStream extends ObjectOutputStream {
public MyObjectOutputStream(OutputStream os) throws IOException {
super(os);
}
#Override
protected void writeStreamHeader() {}
}
interface IIITN {
final String InstituteName = "IIIT Nagpur";
}
class Student implements Serializable
{
String name;
String RollNo;
String branch;
String gender;
String Degree;
Student(String name, String RollNo, String branch, String gender, String Degree) {
this.name = name;
this.RollNo = RollNo;
this.branch = branch;
this.gender = gender;
this.Degree = Degree;
}
}
class CSE implements IIITN {
String name;
public void input(File CSEStudent) throws IOException {
Scanner sc = new Scanner(System.in);
String name = sc.next();
String RollNo = sc.next();
String branch = sc.next();
String gender = sc.next();
String Degree = sc.next();
Student s1 = new Student(name, RollNo, branch, gender, Degree);
FileOutputStream fs = new FileOutputStream(CSEStudent,true);
MyObjectOutputStream obj = new MyObjectOutputStream(fs);
obj.writeObject(s1);
// obj.close();
}
public void display(File f) throws IOException {
FileInputStream CS = new FileInputStream(f);
// ObjectInputStream obj = new ObjectInputStream(CS);
// ArrayList<Student> objectList = new ArrayList<>();
Student s = null;
boolean isExist = false;
ObjectInputStream obj = new ObjectInputStream(CS);
while (!isExist) {
try {
// ObjectInputStream obj = new ObjectInputStream(CS);
s = (Student) obj.readObject();
if (s != null) {
System.out.println(s.name);
}
} catch (Exception e) {
System.out.println();
isExist = true;
}
}
}
public void setname(File f) throws IOException{
System.out.println("Enter the name of student");
Scanner sc = new Scanner(System.in);
this.name = sc.next();
ArrayList<Student> obj = new ArrayList<>();
display(f);
// for (Student student : obj) {
// System.out.println(student.name);
// }
// System.out.println("Enter");
// for (int i = 0; i < obj.size(); i++) {
// if((obj.get(i)).name == this.name) {
// System.out.println((obj.get(i)).name);
// System.out.println((obj.get(i)).RollNo);
// } else {
// System.out.println("Not Found");
// }
// }
}
}
public class Main {
public static void main(String[] args) throws IOException{
CSE c1 = new CSE();
File f = new File("./CSE.txt");
c1.input(f);
c1.input(f);
c1.setname(f);
}
}
It is taking the info of the student and is writing it in the file but when it comes to read from the file it gives me this error
Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 73720007
at java.base/java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:987)
at java.base/java.io.ObjectInputStream.<init>(ObjectInputStream.java:414)
at CSE.display(Main.java:61)
at CSE.setname(Main.java:82)
at Main.main(Main.java:187)
I am trying to learn Java and am really struggling on part of a problem that I have. I am being asked to write a method to read a text file where each line representing an instance of an object e.g. SalesPerson
The question is asking me to add an identifier id for every line that read in, the id is not present in the text file. I have id declared in my Sales Person class with a constructor and getter and setter methods, and have my method to read the text file below in another class. However it doesn't work and I am not sure where I am going wrong. Could someone give me a pointer..? I would be very grateful.,
public static Collection<SalesPerson> readSalesData() {
String pathname = CXU.FileChooser.getFilename();
File aFile = new File(pathname);
Scanner bufferedScanner = null;
Set<SalesPerson> salesSet = new HashSet<>();
try {
int id;
String name;
String productCode;
int sales;
int years;
Scanner lineScanner;
String currentLine;
bufferedScanner = new Scanner(new BufferedReader(new FileReader(aFile)));
while(bufferedScanner.hasNextLine()) {
currentLine = bufferedScanner.nextLine();
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter(",");
id = salesPerson.getId();
name = lineScanner.next(); //return the next token as a string
years = lineScanner.nextInt();
productCode = lineScanner.next(); // return the next token as a string
sales = lineScanner.nextInt(); // return the next token as a double
salesSet.add(new SalesPerson(id, name, years, productCode, sales));
}
}
catch (Exception anException) {
System.out.println("Error: " + anException);
}
finally {
try {
bufferedScanner.close();
}
catch (Exception anException) {
System.out.println("Error: " + anException);
}
}
return salesSet;
}
\\Constructor from Class SalesPerson
public SalesPerson(int aId, String aname, int aYears, String aProductCode, int aSales) {
super(); // optional
this.id = ++nextId;
this.name = aname;
this.years = aYears;
this.productCode = aProductCode;
this.sales = aSales;
}
Please check the following code I tried to make things little more simple:
package com.project;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class Temp {
public static void main(String[] args) {
Set<SalesPerson> salesPersons = (Set<SalesPerson>) readSalesData();
System.out.println(salesPersons.toString());
}
public static Collection<SalesPerson> readSalesData() {
Set<SalesPerson> salesPersons = new HashSet<>();
try {
File file = new File("D:/file.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
if (line.isEmpty())
break;
String[] rowData = line.split(";");
salesPersons.add(new SalesPerson(rowData[0].trim(), Integer.parseInt(rowData[1].trim()), rowData[2].trim(), Integer.parseInt(rowData[3].trim())));
}
fileReader.close();
} catch (Exception ex) {
System.out.println(ex);
}
return salesPersons;
}
}
package com.project;
public class SalesPerson {
// Static to keep reserve value with each new instance
private static int AUTO_ID = 1;
private int id;
private String name;
private int years;
private String productCode;
private int sales;
public SalesPerson() {
}
public SalesPerson(String name, int years, String productCode, int sales) {
this.id = AUTO_ID;
this.name = name;
this.years = years;
this.productCode = productCode;
this.sales = sales;
AUTO_ID++;
}
// Getters & Setters...
#Override
public String toString() {
return "ID: " + id + ", Name: " + name + ", Years: " + years + ", Product Code: " + productCode + ", Sales: " + sales + System.lineSeparator();
}
}
And this my data file:
FullName1 ; 20; p-code-001; 10
FullName2 ; 30; p-code-002; 14
FullName3 ; 18; p-code-012; 1040
public static int processData(ArrayList<String> array)
{
ArrayList <Integer> no=new ArrayList<Integer>();
Iterator it=array.iterator();
String[] strValues;
while(it.hasNext())
{
strValues = array.toString().split(",");
System.out.println(it.next());
strValues = array.toString().split(",");
no.add(0,strValues[2]);
no.add(1,strValues[6]);
strValues = array.toString().split(",");
}
return 1;
}
public static void main (String[] args) {
ArrayList<String> inputData = new ArrayList<String>();
try {
Scanner in = new Scanner(new BufferedReader(new FileReader("D:\\dmo\\input.txt")));
while(in.hasNextLine()) {
String line = in.nextLine().trim();
if (!line.isEmpty()) // Ignore blank lines
inputData.add(line);
}
int retVal = processData(inputData);
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("D:\\dmo\\output.txt")));
output.println("" + retVal);
output.close();
} catch (IOException e) {
System.out.println("IO error in input.txt or output.txt");
}
}
}
Input text file contains records as
20, AB CD ,55 ,876000
22, John carter, 57,987520
23, abrahim ,55,5420130
24,mariya , 55,8952403
25,serena , 57,7895421
This data is passed as Arraylist array to processData() function. I want to calculate avg salary of same department id. Eg. Avg of 55 de
create String str_seperate=""; iterate array with regular exp. do str=array.remove(index); and use Scanner sc=new Scanner(str).useDemiliter("\s*,\W\s*") to find out int and string data..
Creating a person object on each line (assuming each line will have one person data) and adding them into a list. While calculating salary avg per department, first filtering out the persons for that department and then calculating total salary and then dividing by no of persons in that department. Hope it will help.
public class Person {
private int id;
private String name;
private int deptId;
private double salary;
public Person() {
}
public Person(int id, String name, int deptId, double salary) {
this.id = id;
this.name = name;
this.deptId = deptId;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDeptId() {
return deptId;
}
public void setDeptId(int deptId) {
this.deptId = deptId;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
#Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", deptId=" + deptId +
", salary=" + salary +
'}';
}
}
public class Main {
/*public static int processData(ArrayList<String> array) {
ArrayList<Integer> no = new ArrayList<Integer>();
Iterator it = array.iterator();
String[] strValues;
while (it.hasNext()) {
strValues = array.toString().split(",");
System.out.println(it.next());
strValues = array.toString().split(",");
no.add(0, strValues[2]);
no.add(1, strValues[6]);
strValues = array.toString().split(",");
}
return 1;
}*/
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
try {
Scanner in = new Scanner(new BufferedReader(new FileReader("input.txt")));
while (in.hasNextLine()) {
String line = in.nextLine().trim();
if (!line.isEmpty()) // Ignore blank lines
personList.add(getPerson(line));
}
// int retVal = processData(inputData);
// PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
// output.println("" + retVal);
// output.close();
double avgSalary = getAvgSalary(personList, 55);
System.out.println(avgSalary);
} catch (IOException e) {
System.out.println("IO error in input.txt or output.txt");
e.printStackTrace();
}
}
private static Person getPerson(String str) {
String[] strings = str.split(",");
Person person = new Person(Integer.valueOf(strings[0].trim()), strings[1].trim(), Integer.valueOf(strings[2].trim()), Double.valueOf(strings[3].trim()));
System.out.println(person);
return person;
}
private static double getAvgSalary(List<Person> personList, int deptId) {
List<Person> deptPersonList = new ArrayList<>();
for (Person person : personList) {
if (person.getDeptId() == deptId) {
deptPersonList.add(person);
}
}
double totalSalary = 0;
for (Person person : personList) {
totalSalary += person.getSalary();
}
return totalSalary / deptPersonList.size();
}
}
This question already has answers here:
What causes "'void' type not allowed here" error
(7 answers)
Closed 10 months ago.
I am trying to add these data I have read from a file into my map. My map is a treemap TreeMap<String, Student>, where Student in another class. I am trying to use the code map.put(formatSNumber, student.setCourses(courses)); to add the read file elements to my map, but I keep encountering that void type not allowed here error.
sNumber = Integer.parseInt(Breader.readLine());
formatSNumber = String.format("%03d", sNumber);
hours = Integer.parseInt(Breader.readLine());
grade = Double.parseDouble(Breader.readLine());
Student student = map.get(formatSNumber);
Course course = new Course(hours, grade);
List<Course> courses = student.getCourses();
courses.add(course);
map.put(formatSNumber, student.setCourses(courses));
end = Breader.ready();
Here is my full code:
import java.io.*;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.Iterator;
import java.util.List;
public class FinalProgram {
public static void main(String[] args) throws IOException {
String nameFile = " ";
String classFile = " ";
TreeMap<String, Student> map = new TreeMap<>();
Scanner input = new Scanner(System.in);
try {
System.out.print("Enter the Name file(c:filename.txt): ");
nameFile = input.nextLine();
} catch(IllegalArgumentException e) {
System.out.printf("Invalid input. Please enter"
+ " filename in the form of "
+ "c:filename.txt\n", e.getMessage());
}
nameReader(nameFile, map);
try {
System.out.print("Enter the Class file(c:filename.txt): ");
classFile = input.nextLine();
} catch(IllegalArgumentException e) {
System.out.printf("Invalid input. Please enter"
+ " filename in the form of "
+ "c:filename.txt\n", e.getMessage());
}
classReader(classFile, map);
}
private static void nameReader(String file, TreeMap<String, Student> map)
throws IOException {
String nameFile = file;
int sNumber = 0;
String formatSNumber = " ";
String sName = " ";
//Instantiate FileReader and BufferedReader
FileReader freader = new FileReader(nameFile);
BufferedReader Breader = new BufferedReader(freader);
boolean end = Breader.ready();
do {
sNumber = Integer.parseInt(Breader.readLine());
formatSNumber = String.format("%03d", sNumber);
sName = Breader.readLine();
Student student = new Student(sName);
map.put(formatSNumber, student);
end = Breader.ready();
} while(end);
Iterator<String> keySetIterator = map.keySet().iterator();
while(keySetIterator.hasNext()) {
String key = keySetIterator.next();
System.out.println("key: " + key + " value: " + map.get(key).getName());
}
}
private static void classReader(String file, TreeMap<String, Student> map)
throws IOException {
String classFile = file;
int sNumber = 0;
String formatSNumber = " ";
int hours = 0;
double grade = 0.0;
double points = grade * hours;
double GPA = points / hours;
//Instantiate FileReader and BufferedReader
FileReader freader = new FileReader(classFile);
BufferedReader Breader = new BufferedReader(freader);
boolean end = Breader.ready();
do {
sNumber = Integer.parseInt(Breader.readLine());
formatSNumber = String.format("%03d", sNumber);
hours = Integer.parseInt(Breader.readLine());
grade = Double.parseDouble(Breader.readLine());
Student student = map.get(formatSNumber);
Course course = new Course(hours, grade);
List<Course> courses = student.getCourses();
courses.add(course);
map.put(formatSNumber, student.setCourses(courses));
end = Breader.ready();
} while(end);
points = grade * hours;
GPA = points / hours;
}
}
Student class:
import java.util.ArrayList;
import java.util.List;
public class Student {
private String name = " ";
private List<Course> courses = new ArrayList<>();
public Student(String name) {
this.name = name;
}
public Student(String name, List courses) {
this.name = name;
this.courses = courses;
}
public List getCourses() {
return courses;
}
public void setCourses(List courses) {
this.courses = courses;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Course class:
public class Course {
private int hours = 0;
private double grade = 0.0;
public Course(int hours, double grade) {
this.hours = hours;
this.grade = grade;
}
public void setHours(int hours) {
this.hours = hours;
}
public int getHours() {
return hours;
}
public void setGrade(double grade) {
this.grade = grade;
}
public double getGrade() {
return grade;
}
}
The second argument in map.put(formatSNumber, student.setCourses(courses)) must be of type Student. student.setCourses(courses) is a setter method with return type void, i.e. no return. This does not match.
You must have something like map.put("someString", new Student("name")) for instance, or map.put("someString", student) where student is of type Student.
The idea of put is about putting something into that Map.
More precisely, you typically provide (non-null) key and a value objects.
You are using student.setCourses(courses) as argument for that "value" parameter that put() expects.
That argument is an expression. And the result of that expression would be the result of the method call.
That method is defined to not return anything (void that is).
Obviously nothing is not the same as something. And that is what the compiler tries to tell you.
Two solutions:
pass a Student object
change that method setCourses()
Like this:
Student setCourses(... {
....
return this;
}
( you better go for option 1; 2 is more of a dirty hack, bad practice in essence )
In netbeans I got an Array Index Out Of Bounds Exception error in my code at line 35 in the MyProj03 class from line 55 in the Person class. I am not sure why I am getting this error.
My code:
import java.util.Scanner;
import java.io.*;
import birch.Person.*;
public class MyProj03 {
public static void main(String[] args) throws IOException {
// check for file existence
File file = new File("p3text.txt");
if (file.exists())
{
// read each record into a String
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner("p3text.txt");
String lineSeparator = System.getProperty("line.separator");
try {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
Person one = new Person();
one.parseCommaDelim(fileContents.toString());
}
} finally
{
scanner.close();
}
}
else if (!file.exists())
{
System.out.println("The file p3text.txt is not found.");
System.exit(2);
}
}
}
more code:
public class Person {
//make instance fields for name, city, age, and SiblingCount
public String name;
public int age;
public String city;
public int sibCount;
public Person()
{
name = "";
age = 0;
city = "";
sibCount = 0;
}
// public access methods (getters)
public String getPerson() {
return this.name;
}
public int getAge() {
return this.age;
}
public String getCity() {
return this.city;
}
public int getSibCount() {
return this.sibCount;
}
// make a toString method
public String toString()
{
String str = "person: " + name + "age: " + age + "city: " + city;
return str;
}
// make a method called parseCommaDelim
public Person parseCommaDelim(String s) {
String[] tokens = s.split(",");
Person instance = new Person();
instance.name = tokens[0];
instance.age = Integer.parseInt(tokens[1]); //ArrayIndexOutOfBoundsException error
instance.city = tokens[2];
instance.sibCount = Integer.parseInt(tokens[3]);
return instance;
}
public int getIndex(Arrays list[], String key)
{
for (int index = 0; index< list.length; index++)
{
if ( list[index].equals(key) )
return index;
}
return -1;
}
}
My text file
Rhonda, 20 , San Diego , 1
Kaitlin, 24 , Provo , 4
Bret, 24 , Columbia , 4
Chris, 28 , Escondido , 2
Dylan, 21, Portland, 3
You can scan file's content line by line and process with this code:
public class MyProj03 {
public static void main(String[] args) throws IOException {
File file = new File("p3text.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Person one = new Person();
one.parseCommaDelim(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
also I recommend you to change the fragment codes :
Person instance = new Person();
instance.name = tokens[0];
instance.age = Integer.parseInt(tokens[1]); //ArrayIndexOutOfBoundsException error
instance.city = tokens[2];
instance.sibCount = Integer.parseInt(tokens[3]);
to this:
Person instance = new Person();
instance.name = tokens[0];
instance.age = Integer.parseInt(tokens[1].trim()); //ArrayIndexOutOfBoundsException error
instance.city = tokens[2];
instance.sibCount = Integer.parseInt(tokens[3].trim());
You should replace
Person one = new Person();
one.parseCommaDelim(lineSeparator);
with
Person one = new Person();
one.parseCommaDelim(fileContents.toString());
as your current implementation tries to parse the , itself, not the string your read.