Error while file reading - java

I wanna make an ArrayList of objects of my own class named Room and store it to file. I have successfully wrote it but when I read it back to ArrayList it gives me the following error
error: incompatible types
temp_read=filereader.readObject();
^
required: Room
found: Object
My code:
public class Room implements Serializable
{
public String room_number="";
public String teacher_name="";
public String Day_of_class="";
public String class_name="";
public My_Time start_time;
public My_Time end_time;
public Room()
{
room_number="";
teacher_name="";
Day_of_class="";
class_name="";
start_time=new My_Time();
end_time=new My_Time();
}
public Room(String r_name ,String t_name ,String cl,String day,
int hr1,int min1,String am1,int hr2,int min2,String am2 )
{
room_number=r_name;
teacher_name=t_name;
Day_of_class=day;
class_name=cl;
start_time=new My_Time(hr1,min1,am1);
end_time=new My_Time(hr2,min2,am2);
}
public void file_room_writer(/* ArrayList<Room> temp_room ,*/String str )
{
/// file writing handling`enter code here`
//--------------------------------------------------
// Room a1 =temp_room;
try {
File file = new File(str+".txt");
FileOutputStream file_stream=new FileOutputStream(file);
ObjectOutputStream fileWriter = new ObjectOutputStream(file_stream);
fileWriter.writeObject(class_storing);
fileWriter.close();
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(null,"Exception at file writing ");
}
}
public void file_room_reader(String str )
{
/// file handlingg
//--------------------------------------------------
ArrayList<Room> contain_room ;
try {
File file = new File(str+".txt");
FileInputStream file_stream=new FileInputStream(file);
ObjectInputStream filereader = new ObjectInputStream(file_stream);
temp_read=filereader.readObject();
contain_room=(ArrayList<Room>)filereader.readObject();
filereader.close();
}
catch(Exception e1)
{
e1.getStackTrace();
JOptionPane.showMessageDialog(null,"Exception at file Reading ");
}
}

The readObject method returns an object - you have to try and cast it to a Room.
temp_read = (Room) filereader.readObject();

readObject() returns Object , you'll have to downcast it to the type of temp_read.
Assuming Room is the type of temp_read
temp_read = (Room) filereader.readObject();

Related

Java Streams read files and print objects read on files

So guys i need some help. I have a class Book and i want to save my books object to a Stream and then read this Stream file so i can search my objects from there. I have written my code but it gives me some errors and i can figure out how to print my books values .
So this is my Book class
public class Book {
private Date arr;
private Date depp;
private Type room;
private boolean breakfast = false;
private Person data;
private ObjectOutputStream out;
public Book(String name, String surename, String phone,Date arr, Date depp, Type room, boolean breakfast) {
data = new Person(name,surename,phone);
this.arr = arr;
this.depp = depp;
this.room = room;
this.breakfast = breakfast;
}
public void writeObjToFile(){//here i save my object to stream it gives me error, i call this method after i create my book object to main
try{
out = new ObjectOutputStream(new FileOutputStream("books.txt"));
out.writeObject(this);
}
catch(FileNotFoundException e){
System.err.println("File not Found");
e.printStackTrace();
}catch(IOException e){
System.err.println("IOException");
e.printStackTrace();}
}
}
and this is my Search class :
public class Search {
private FileInputStream fis=null;
private String filename;
public Search(String filename){
this.filename = filename;
File file = new File(filename);
try {
fis = new FileInputStream(file);
System.out.println("Total file size to read (in bytes) : "
+ fis.available());
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Book should implement Serializable
Check the API
https://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html#writeObject%28java.lang.Object%29
Also, remove the out member from Book class because it's not Serializable either.

Best approach of reading data from text file and adding it to arraylist in android

I am working on a project to get into android development, having some knowledge of java before I am thinking of reading data from a text file, which will be formatted like this;
Type: House
Image link: www.bit.ly/image1
Name: Black
Download Link: www.bit.ly/image1download
----------
Type: Car
Image link: www.bit.ly/image2
Name: yellow
Download Link: www.bit.ly/image2download
----------
Type: Backyard
Image link: www.bit.ly/image3
Name: Green
Download Link: www.bit.ly/image3download
----------
Type: Window
Image link: www.bit.ly/image4
Name: Solid
Download Link: www.bit.ly/image4download
----------
Type: Table
Image link: www.bit.ly/image5
Name: Brown
Download Link: www.bit.ly/image5download
----------
The data contains 4 pieces of information per set, Type, Image, Name and Download. I need a way of reading this and saving/writing it to a arraylist which I then can display in a listview that I will have on my app. (I am currently looking at tutorials on creating listview, if you know any useful tutorials please let me know)
Arraylist <String> data = new ArrayList<String>();
Data.add(“House”,” www.bit.ly/image1”,”black”,”www.bit.ly/image1download”);
Data.add(“Car”,” www.bit.ly/image2”,”yellow”,” www.bit.ly/image2download”);
……..
……..
In reality there will be a lot more data then just 5 sets , so I want to use for loop to loop through each data data and add it to the data arraylist.
I am not sure how I can approach this, any help is welcomed, I am really stuck. Please let me know if I have not explained my question properly.
EDITED:
Would this be the correct way of reading data from a textfile?
Scanner content = new Scanner(new File("Data.txt"));
ArrayList<String> data = new ArrayList<String>();
while (content.hasNext()){
data.add(content.next());
}
content.close();
Or is this another way in android
Before start go through this link for reading
How can I read a text file in Android?
Use PoJo Models for your needs,
Create a PoJo class like this
public class Film {
private String filmName;
private String mainStar;
public String getFilmName() {
return filmName;
}
public void setFilmName(String filmName) {
this.filmName = filmName;
}
public String getMainStar() {
return mainStar;
}
public void setMainStar(String mainStar) {
this.mainStar = mainStar;
}
}
Create ArrayList
private ArrayList<Film > filmArray=new ArrayList<Film>();
Store Each arraylist with instance of your PoJo class like this
for(int i=0;i<sizei++)
{
Film film=new Film();
film.setFilmName("your value");
film.setMainStar("your value");
filmArray.add(film);
}
and then access list of values in arraylist of PoJo class in filmArray list.
Simple and elegant solution.
Here is the parser
public class FileParser {
private static final String DATA_TERMINATION = "----------";
private static final String TYPE="Type";
private static final String IMAGE="Image link";
private static final String NAME= "Name";
private static final String DWNLD_LNK= "Download Link";
public static void main(String[] args) {
FileParser parser = new FileParser();
try {
for(Data d:parser.parseDataFile(new File("F:\\data.txt"))){
System.out.println(TYPE+":"+d.getType());
System.out.println(IMAGE+":"+d.getImage());
System.out.println(NAME+":"+d.getName());
System.out.println(DWNLD_LNK+":"+d.getLink());
System.out.println(DATA_TERMINATION);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List<Data> parseDataFile(File input) throws Exception{
List<Data> output =null;
List<String> fileOp= null;
try {
validateInput(input);
fileOp = readFile(input);
output = parseData(fileOp);
} catch (Exception e) {
throw e;
}
return output;
}
private List<Data> parseData(List<String> fileOp) {
List<Data> output =null;
output = new ArrayList<Data>();
Data data;
data = new Data();
for(String line:fileOp){
if(DATA_TERMINATION.equalsIgnoreCase(line)){
output.add(data);
data = new Data();
}else{
parseField(data,line);
}
}
return output;
}
private void parseField(Data data, String line) {
StringTokenizer tokenzr = new StringTokenizer(line,":");
if(tokenzr.countTokens() !=2){
System.out.println("Cant parse line"+line);
}else{
switch (tokenzr.nextToken()) {
case TYPE:
data.setType(tokenzr.nextToken());
break;
case IMAGE:
data.setImage(tokenzr.nextToken());
break;
case NAME:
data.setName(tokenzr.nextToken());
break;
case DWNLD_LNK:
data.setLink(tokenzr.nextToken());
break;
default:
break;
}
}
}
private List<String> readFile(File input) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input)));
String line = null;
List<String> op = new ArrayList<String>();
try {
while((line = reader.readLine()) != null){
op.add(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw e;
}
return op;
}
private void validateInput(File input) throws Exception {
if(input == null){
throw new Exception("Null input");
}else if(!input.exists() || !input.isFile() || !input.canRead() ) {
throw new Exception("File not readable");
}
}
}
Do this way define a setter getter class to hold and return values like this :
Data.class
public class Data {
String type,Image,Name,Link ;
public Data() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getLink() {
return Link;
}
public void setLink(String link) {
Link = link;
}
}
using for loop set data in a arraylist
Arraylist <Data> arrayListData = new ArrayList<Data>();
for(int i=0;i<arrayListData .size();i++){
Data data=new Data();
data.setType("");
...
...
...
arrayListData.add(data);
}
and to fetch data from arraylist
String type= arrayListData.get(position).getType();
Updated :
read .txt file like this , I am assuming your text file is saved in sdcard of device :
public void readfile() {
StringBuilder text = new StringBuilder();
File sdcard = Environment.getExternalStorageDirectory();
ArrayList<Data> arrayList=new ArrayList<Data>();
//Get the text file
File file = new File(sdcard,"textfile.txt");
//Read text from file
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
Data data=new Data();
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
if(line.contains(":")){
int index=line.indexOf(":");
String s=line.substring(index+1).trim();
if(line.contains("Type")){
data.setType(s);
}
if(line.contains("Image")){
data.setImage(s);
}
if(line.contains("Name")){
data.setName(s);
}
if(line.contains("Download")){
data.setLink(s);
}
}
if(line.contains("-")){
arrayList.add(data);
data=new Data();
}
}
System.out.println(text);
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}

Serialized Object File Output is empty

I am trying to create a file that stores high scores for a game that I am making. I am using a serializer to write my arrays into a file. The file is created upon running my code but the file is empty (0 bytes). I'm not getting any errors. Can anyone tell me why the file does not contain my data?
public class BestTimes implements Serializable
{
BestTimes[] beginner = new BestTimes[2];
public static void main(String args[]) throws IOException {
BestTimes bestTimes = new BestTimes();
bestTimes.outputToFile();
}
public BestTimes() {
beginner[0] = new BestTimes(1, "John", 10.5);
beginner[1] = new BestTimes(2, "James", 20.3);
}
public int ranking;
public String playerName;
public double time;
public BestTimes(int r, String p, double t)
{
ranking = r;
playerName = p;
time = t;
}
public void outputToFile() throws IOException {
try(FileOutputStream f = new FileOutputStream("bestTimes.txt")) {
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(beginner);
s.flush();
s.close();
} finally {
FileOutputStream f = new FileOutputStream("bestTimes.txt");
f.close();
}
}
}
Of course it's empty. You created a new one in the finally block.
Just remove that code.

Java ClassCastException while using FileInputStream

I am trying to save/load instances of my TicketSet class in Java. Below is the class and the class variables. The Ticket and Variable class are also Serializable.
public class TicketSet implements Serializable{
public final int setID;
public int ticketNum;
public Ticket[] tickets;
private static int xCount[];
private static int yCount[];
private static int zCount[];
private Variable x;
private Variable y;
private Variable z;
In another class I save an instance of the TicketSet class which seems to work fine. In the code, gen is just an instance of a controller class which initialises TicketSet.
TicketSet set;
if (f.exists()) {
FileOutputStream fileOut =new FileOutputStream(f,true);
AppendingObjectOutputStream out = new AppendingObjectOutputStream(fileOut);
set = gen.getTSet();
out.writeObject(set);
out.close();
fileOut.close();
} else {
FileOutputStream fileOut =new FileOutputStream(f,true);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
set = gen.getTSet();
out.writeObject(set);
out.close();
fileOut.close();
}
To load the instances of TicketSet, I have the following code which throws the error.
ArrayList<Integer> tickid = new ArrayList<Integer>();
tSets = new HashMap<Integer, TicketSet>();
FileInputStream fileStr = null;
ObjectInputStream reader = null;
try {
fileStr = new FileInputStream("TicketSets.ser");
reader = new ObjectInputStream(fileStr);
System.out.println(fileStr.available());
TicketSet tSet= null;
while (fileStr.available()>0) {
Object next = reader.readObject(); //ERROR HERE
if (next instanceof TicketSet) {
tSet = (TicketSet) next;
System.out.println("ID: "+tSet.setID);
tSets.put(tSet.setID, tSet);
tickid.add(tSet.setID);
} else {
System.out.println("Unexpected object type: " + next.getClass().getName());
}
}
//System.out.println("Size: "+tSets.size());
reader.close();
fileStr.close();
}
catch(IOException i) {
i.printStackTrace();
}
catch (ClassNotFoundException c) {
System.out.println("TicketSet class not found");
c.printStackTrace();
}
The error thrown is:
ID: 7325825
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.io.ObjectStreamClass
So what I understand is:
The first TicketSet is loaded fine... which has ID=73225825
It is then trying to load an integer from the file rather than a TicketSet object.
Why is it trying to load an integer? Is there a way to skip reading anything other than objects? Should I try an alternative approach?
I was missing the Reset() in my AppendingObjectOutputStream.
ClassCastException when Appending Object OutputStream

Serilization Operations

I want to print list of data in file
List<TimeSheetVO> timesheetlist;
java.sql.Date dbdateformat = null;
String date="2013-02-06";
timesheetlist=new ArrayList<TimeSheetVO>();
java.sql.Date dbdate=java.sql.Date.valueOf(date);
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://192.168.1.101:3306/bio_tracker_eden","eden","centris");
String query = "select * from ai_bio_timesheet where ATTENDANCE_DATE=?";
PreparedStatement psmt=con.prepareStatement(query);
psmt.setDate(1,dbdate );
ResultSet rs=psmt.executeQuery();
while(rs.next())
{
timeSheetVO =new TimeSheetVO();
timeSheetVO.setEMP_ID(rs.getString("EMP_ID"));
timeSheetVO.setATTENDANCE_DATE(rs.getString("ATTENDANCE_DATE"));
timeSheetVO.setIN_TIME(rs.getTime("IN_TIME"));
timeSheetVO.setOUT_TIME(rs.getTime("OUT_TIME"));
timesheetlist.add(timeSheetVO);
File file=new File("D:/timesheet.txt");
ObjectOutputStream outstream=new ObjectOutputStream(new FileOutputStream(file));
outstream.writeObject(timesheetlist);
outstream.flush();
outstream.close();
}
}catch (Exception e) {
e.printStackTrace();
}
Here I retrieve the data from database and store the data into list and that list is stored in to file.
But the file is not stored the values.
Can you explain where the problem is?
Here values are coming from database but not displayed in file
I use the below class:
public class TimeSheetVO implements Serializable{
private String EMP_ID;
private String ATTENDANCE_DATE;
private Time IN_TIME;
private Time OUT_TIME;
private Time TOTAL_HOURS;
public String getEMP_ID() {
return EMP_ID;
}
public void setEMP_ID(String eMP_ID) {
EMP_ID = eMP_ID;
}
public String getATTENDANCE_DATE() {
return ATTENDANCE_DATE;
}
public void setATTENDANCE_DATE(String aTTENDANCE_DATE) {
ATTENDANCE_DATE = aTTENDANCE_DATE;
}
public Time getIN_TIME() {
return IN_TIME;
}
public void setIN_TIME(Time iN_TIME) {
IN_TIME = iN_TIME;
}
public Time getOUT_TIME() {
return OUT_TIME;
}
public void setOUT_TIME(Time oUT_TIME) {
OUT_TIME = oUT_TIME;
}
public Time getTOTAL_HOURS() {
return TOTAL_HOURS;
}
public void setTOTAL_HOURS(Time tOTAL_HOURS) {
TOTAL_HOURS = tOTAL_HOURS;
}
#Override
public String toString() {
return new StringBuffer().append(EMP_ID).
append("\n").
append(ATTENDANCE_DATE).
append("\n").
append(IN_TIME).
append("\n").
append(OUT_TIME).toString();
}
}
Here printing the values in file:
[72013-02-0617:50:1519:19:15
, 132013-02-0619:02:1119:02:25
, 212013-02-0618:25:2218:25:22
, 282013-02-0618:25:4318:25:43
, 442013-02-0619:20:2019:41:21
, 562013-02-0617:54:0817:54:08
]
But I want to print like this:
72013-02-0617:50:1519:19:15
132013-02-0619:02:1119:02:25
212013-02-0618:25:2218:25:22
282013-02-0618:25:4318:25:43
442013-02-0619:20:2019:41:21
562013-02-0617:54:0817:54:08
Here am append \n but new line is not coming
Your serialization works fine, I tested locally, you should be able to re create List of TimeSheetVO by doing deserialization.
Primary purpose of java serialization is to write an object into a
stream, so that it can be transported through a network and that
object can be rebuilt again
If you want write the only content of the object in to file, then you would not require serialization, rather write obj.data as plain text in to file.
--- EDIT--
Can you put serialization code outside while loop?
while(rs.next())
{
timeSheetVO =new TimeSheetVO();
timeSheetVO.setEMP_ID(rs.getString("EMP_ID"));
timeSheetVO.setATTENDANCE_DATE(rs.getString("ATTENDANCE_DATE"));
timeSheetVO.setIN_TIME(rs.getTime("IN_TIME"));
timeSheetVO.setOUT_TIME(rs.getTime("OUT_TIME"));
timesheetlist.add(timeSheetVO);
}
File file=new File("D:/timesheet.txt");
ObjectOutputStream outstream=new ObjectOutputStream(new FileOutputStream(file));
outstream.writeObject(timesheetlist);
outstream.flush();
outstream.close();

Categories

Resources