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)
Related
I'm supposed to write a program that asks for people's name and age and then prints the oldest person's name. (Sorry some parts of the programming are not in english, but I hope someone understands enough to help). It's an assignment and I have to do it by splitting the string.
The print should be like this:
James,2
Mary,2
Jessica,1
Jennifer,5
Gabriel,10
The name of the oldest: Gabriel
I know how to print the highest age, but not the name of it. This is how i've done it:
public static void main(String[] args) {
Scanner lukija = new Scanner(System.in);
int oldest = -1;
while (true) {
String mjono = lukija.nextLine();
if (mjono.equals("")) {
break;
}
String[] pieces = mjono.split(",");
int age = Integer.valueOf(pieces[1]);
if (age > oldest) {
oldest = age;
}
}
System.out.println("The oldest age: " + oldest);
Let's say we have the input of:
James,2
Mary,2
Jessica,1
Jennifer,5
Gabriel,10
We can read line by line and then get the oldest person by the following class:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.*;
public class OldestPerson {
public static class Person {
private String name;
private int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return this.age;
}
public String getName() {
return this.name;
}
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
PriorityQueue<Person> queue = new PriorityQueue<Person>((a, b) -> b.getAge() - a.getAge());
while ((line = reader.readLine()) != null) {
String[] tmp = line.split(",");
queue.add(new Person(tmp[0], Integer.parseInt(tmp[1])));
}
if (!queue.isEmpty()) {
Person oldestPerson = queue.poll();
System.out.println(oldestPerson.getName());
}
}
}
Another way to do that is simply comparing the person age directly:
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
String oldestPerson = "";
int age = Integer.MIN_VALUE;
while ((line = reader.readLine()) != null) {
String[] tmp = line.split(",");
if (age < Integer.parseInt(tmp[1])) {
age = Integer.parseInt(tmp[1]);
oldestPerson = tmp[0];
}
}
System.out.println(oldestPerson);
}
I'm having a number of issues with this:
1) Under which class would I want to put my Scanner, so that it assigns the proper variables? The task I am given says to "read data file into Students" in the Tester class
2) How can I make a readFile() method in the Students class?
3) How can I properly write toString() in both Student and Students classes?
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[]) throws IOException
{
//new Students object
Students theStudents = new Students();
//reads file from Students
theStudents.readFile();
// create new 'Output.txt' file to save program output
PrintWriter ot = new PrintWriter(new FileWriter("Output.txt"));
System.out.println(theStudents.toString());
ot.println(theStudents.toString());
ot.close();
}
}
import java.util.ArrayList;
import java.io.*;
import java.util.*;
import java.io.FileReader;
public class Students
{
// instance variables
private ArrayList<Student> students;
public Students()
{
//create arraylist for students
students = new ArrayList<>();
}
public void readFile() throws IOException
{
String name;
int age;
double gpa;
String line;
//Scanner to read file
try {
Scanner sc = new Scanner(new File("Students.txt"));
while (sc.hasNextLine()) {
name = sc.nextLine();
line = sc.nextLine();
age = Integer.parseInt(line);
line = sc.nextLine();
gpa = Double.parseDouble(line);
}
}
catch (FileNotFoundException e) {
System.out.println("Error");
}
}
public void add(Student s)
{
students.add(s);
}
public Students aboveAverage(double avgGPA)
{
Students aboveAverage = new Students();
for (int i = 0; i < students.size(); ++i) {
if (students.get(i).getGPA() > avgGPA)
aboveAverage.add(students.get(i));
}
return aboveAverage;
}
public String toString()
{
String out = "";
int count = 0;
for (Student student : students){
out += students.toString() + " ";
++count;
}
return out;
}
}
public class Student
{
private String name;
private int age;
private double gpa;
public Student(String studentName, int studentAge, double studentGPA)
{
name = studentName;
age = studentAge;
gpa = studentGPA;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public double getGPA()
{
return gpa;
}
public String toString()
{
return String.format("%10s", name) +
String.format("%5d", age) + String.format("%10.2f \n", gpa);
}
}
I'm not gonna give you the complete solution but here is a way to approach this problem.
You need readLine() instead of nextLine()
Once you read the values, you need to call the add() function with the Student Object to add it to your ArrayList.
Code Snippet:
try (Scanner sc = new Scanner(new File("Students.txt"))) {
while (sc.hasNextLine()) {
String name = sc.readLine();
int age = Integer.parseInt(sc.readLine());
double gpa = Double.parseDouble(sc.readLine());
/* Create A New Student Object & Add To List */
add(new Student(name, age, gpa));
}
} catch (FileNotFoundException e) {
System.out.println("Error");
}
Also, you need to #Override the toString() function.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class gTextFile {
static LinkedList<gText> list = new LinkedList<gText>();
public static void main(String[] args) throws FileNotFoundException {
Scanner scnOne = new Scanner(System.in);
String eCode;
System.out.print("Employee Code: ");
eCode = scnOne.nextLine();
readFile();
gEmpName("eCode");
}
public static void readFile() throws FileNotFoundException {
File nFile = new File("C:\\JAVAP\\GetTextFile\\employee.txt");
Scanner scnTwo = new Scanner(nFile);
String oTemp;
while(scnTwo.hasNext()) {
oTemp = scnTwo.next();
String EmCode[] = oTemp.split(" ");
String Name[] = EmCode[1].split(",");
String idCode = EmCode[0];
String lastname = Name[0];
String firstname = Name[1];
//System.out.println("FName " + firstname);
//System.out.println("LName " + lastname);
gText gT = new gText(firstname, lastname, idCode);
list.add(gT);
}
scnTwo.close();
}
public static void gEmpName(String EmpCode) {
Iterator<gText> itr = list.iterator();
while(itr.hasNext()) {
gText gT = itr.next();
if(gT.id.equals(EmpCode)){
System.out.println("Employee Name: " + gT.Fname + " " + gT.Lname);
}
}
}
}
public class gText {
String Fname;
String Lname;
String id;
gText(String First, String Last, String ID) {
this.Fname = First;
this.Lname = Last;
this.id = ID;
}
public String gFName() {
return Fname;
}
public String gLName() {
return Lname;
}
public String gId() {
return id;
}
}
What are the problem in my code?? the specific code doesn't show out when I run my program. It always say that there are problem. This always come out in the console, when I put the Employee Code.
Employee Code: A11-0001
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at gTextFile.readFile(gTextFile.java:28)
at gTextFile.main(gTextFile.java:17)
Use oTemp = scnTwo.nextLine(); instead of oTemp = scnTwo.next(); in your readFile() method. When using next() you are just getting what comes before first space, in your case only employee code, so use nextLine() to fetch complete line. For more clarification on difference between next() and nextLine(), refer below link
What's the difference between next() and nextLine() methods from Scanner class?
Also, you may want to use gEmpName(eCode); instead of gEmpName("eCode");
Following is the code:
public class gTextFile {
static LinkedList<gText> list = new LinkedList<gText>();
public static void main(String[] args) throws FileNotFoundException {
Scanner scnOne = new Scanner(System.in);
String eCode;
System.out.print("Employee Code: ");
eCode = scnOne.nextLine();
readFile();
gEmpName(eCode);
}
public static void readFile() throws FileNotFoundException {
File nFile = new File("/home/path/abc.txt");
Scanner scnTwo = new Scanner(nFile);
String oTemp;
while(scnTwo.hasNext()) {
oTemp = scnTwo.nextLine();
String EmCode[] = oTemp.split(" ");
String Name[] = EmCode[1].split(",");
String idCode = EmCode[0];
String lastname = Name[0];
String firstname = Name[1];
gText gT = new gText(firstname, lastname, idCode);
list.add(gT);
}
scnTwo.close();
}
public static void gEmpName(String EmpCode) {
Iterator<gText> itr = list.iterator();
while(itr.hasNext()) {
gText gT = itr.next();
if(gT.id.equals(EmpCode)){
System.out.println("Employee Name: " + gT.Fname + " " + gT.Lname);
}
}
}
}
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();
}
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.