In Java FileWriter and FileReader, Is it possible to use object? - java

Please consider these codes: Is it possible to use FileWriter and FileReader with object of class student?
Student s1 = new Student();
s1.input();//I want to write this method in a File
FileWriter out2 = new FileWriter("input.txt");
out2.write();
out2.flush();
out2.close();
s1.display();//I want to Read this method in a File
FileReader in2 = new FileReader("input.txt");
in2.read();
in2.close();

Yes, you can save any Object you like with FileOutputStream and get it with FileInputStream (as Object, you need casting after this). Just try it out.
As an example:
FileOutputStream fos = null;
ObjectOutputStream writer = null;
Student data = new Student();
try{
fos = new FileOutputStream(fileName);
writer = new ObjectOutputStream(fos);
writer.writeObject(data);
}
catch (IOException ex){
ex.printStackTrace();
}
Just remember closing it and doing the exception exercise :-).
Since I found an old full-working example-class you may want have a look into it (that's pretty ugly code, but it does the job):
import java.io.*;
public class Test {
static boolean checkFile(File file) {
if (file != null) {
if(file.isFile()){
return true;
}
try {
file.createNewFile();
} catch (IOException e) {
System.err.println("Error creating " + file.toString());
}
if (file.isFile() && file.canWrite() && file.canRead())
return true;
}
return false;
}
static boolean writeFile(String dat, Object data){
FileOutputStream fos = null;
ObjectOutputStream writer = null;
try{
fos = new FileOutputStream(dat);
writer = new ObjectOutputStream(fos);
writer.writeObject(data);
}
catch (IOException ex){
ex.printStackTrace();
return false;
}
finally{
try{
if(writer!=null){
writer.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
try{
if(fos!=null){
fos.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
}
return true;
}
static Student readFile(String dat){
FileInputStream fis = null;
ObjectInputStream reader = null;
Student student = null;
try{
fis = new FileInputStream(dat);
reader = new ObjectInputStream(fis);
student = (Student) reader.readObject();
}
catch (Exception ex){
ex.printStackTrace();
}
finally{
try{
if(reader!=null){
reader.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
try{
if(fis!=null){
fis.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
}
return student;
}
public static void main(String[] args){
Student student = new Student("Horst");
String filename = "input.txt";
boolean worked = false;
if(checkFile(new File(filename)))
worked=writeFile(filename, student);
student = new Student("not Horst");
if(worked)
student= (Student) readFile(filename);
System.out.println("Student : " + student.name);
}
}
class Student implements Serializable{
public String name;
public Student(String name){
this.name=name;
}
}

Related

Write JSON Object to file- append not working

I'try to save my custom JSONObject into the file.Everything working correct but I can't append json into file.For example,If I click twice to save json,in my file I have one element.Here is a my source
public class TransactionFileManager {
public static final File path = Environment.
getExternalStoragePublicDirectory(Environment.getExternalStorageState() + "/myfolder/");
public static final File file = new File(path, "transaction1.json");
public static String read() {
String ret = null;
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
try {
String receiveString;
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
ret = stringBuilder.toString();
bufferedReader.close();
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
try {
file.createNewFile();
} catch (IOException ioe) {
ioe.printStackTrace();
}
e.printStackTrace();
}
return ret;
}
public static void writeToFile(JSONObject data) {
if (!path.exists()) {
path.mkdirs();
}
try {
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fOut);
outputStreamWriter.append(data.toString());
outputStreamWriter.close();
fOut.flush();
fOut.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
}
How I can append json object into my .json file.What's a wrong in my code
thanks

How create multiple serialization?

How create multiple serialization ? Now the system write just last record to txt. I want create simple DB that will contain customers info. And what you think, about this method of storing data in txt. ?
private static void WriteCustomers(){
System.out.println("|______Registration module______|");
try {
System.out.println("First name: ");
String firstName = reader.readLine();
System.out.println("Last name: ");
String lastName = reader.readLine();
.....
CustomerManagement obj = new CustomerManagement();
CustomerManagementD customerManagementD = new CustomerManagementD();
customerManagementD.setFirstName(firstName);
customerManagementD.setLastName(lastName);
.....
obj.serializeCustomers(customerManagementD);
}catch (IOException e){
e.getMessage();
}
}
public void serializeCustomers(CustomerManagementD customerManagementD) {
FileOutputStream fout = null;
ObjectOutputStream oos = null;
try {
fout = new FileOutputStream("CustomerManagement.txt");
oos = new ObjectOutputStream(fout);
oos.writeObject(customerManagementD);
System.out.println("Done");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (fout != null) {
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Last question, If I use serialization, I will be able to Edit and Remove stored particular objects?
A txt-file is used for text-only. The ObjectOutputStream stores more than then fields: it stores the classname (and serialVersionUID if present). Try to use .dat what is a generic extension for databases or datas.
You call the method serializeCustomers where Customers is plural and let me think we can store multiple Customer, but the parameter does not allow to use multiple customers. Instead, I suggest, to store a Set (like a LinkedHashSet) to store multiple customers, and yes, you can read and write to the LinkedHashSet.
SOLUTION
private static void WriteCustomers(List<CustomerManagementD> list){
try {
System.out.println("First name: ");
String firstName = reader.readLine();
System.out.println("Last name: ");
String lastName = reader.readLine();
.....
// serialize collection of customers
customerManagementDArraysList.add(new CustomerManagementD(
customerID,firstName,lastName,email,contactNo));
ObjectOutputStream outStream = null;
try {
outStream = new ObjectOutputStream(new FileOutputStream(file));
for (CustomerManagementD p : list) {
outStream.writeObject(p);
}
} catch (IOException ioException) {
System.err.println("Error opening file.");
} finally {
try {
if (outStream != null)
outStream.close();
} catch (IOException ioException) {
System.err.println("Error closing file.");
}
}
}else if (finalcheck.equals("2")){
Adminswitch();
}
System.out.println("|______Customer was successfully saved______|\n Press 'Enter' to continue...");
String absentinput = reader.readLine();
Adminswitch();
}catch (IOException e){
e.printStackTrace();
}
}
private static ArrayList ViewCustomer(){
try{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream oos =new ObjectInputStream(fis);
ArrayList<CustomerManagementD> customerManagementDArraysList = new ArrayList<>();
try {
while (true) {
CustomerManagementD cmd = (CustomerManagementD) oos.readObject();
customerManagementDArraysList.add(cmd);
}
}catch (EOFException e){
e.getMessage();
}
{
while (file.canRead()){
for (CustomerManagementD cmd : customerManagementDArraysList) {
System.out.println("Customer ID: " + cmd.getCustomerID() +
" First Name: " + cmd.getFirstName() +
" Last Name: " + cmd.getLastName()+....);
}
break;
}
}
}catch (IOException e){
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();}
return null;
}

FileOutputStream creates a file, but FileInputStream

I am using a FileOutputStream to create a file in an activity that is not my MainActivity. The file is created, and when I destroy the activity, the data I want is written, but when I relaunch the activity from my MainActivity, the file cannot be found. What can I change in my code so that I don't get a fileNotFoundException? The relevant code is here:
try {
fis = new FileInputStream("words");
ois = new ObjectInputStream(fis);
} catch (FileNotFoundException e1) {
fnfexception = e1;
} catch (IOException ioe) {
ioe.printStackTrace();
}
EOFException eof = null;
int counter = 0;
if (fnfexception == null) {
while (eof == null) {
try {
if (words == null) words = new Dict[1];
else words = Arrays.copyOf(words, counter + 1);
words[counter] = (Dict) ois.readObject();
counter++;
} catch (EOFException end) {
eof = end;
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
}
wordStartCount = counter;
wordCount = counter;
fnfexception = null;
try {
fos = openFileOutput("words", Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
} catch (FileNotFoundException e1) {
fnfexception = e1;
} catch (IOException ioe) {
ioe.printStackTrace();
}
You used wrong way to read from an internal file, use the following code
try {
FileInputStream fis = context.openFileInput("file_name");
int content;
StringBuilder str = new StringBuilder();
while ((content = fis.read()) != -1)
str.append((char) content);
fis.close();
String savedText = str.toString();
} catch (IOException e) {
e.printStackTrace();
}

ArrayList Serializable with Java

I have a problem, I'd like to serialize an ArrayList with Java to a file.
then I'd like to deserialize it to a new ArrayList and continue to add to the ArrayList.
When I deserialize, it doesn't load in the ArrayList, it just prints the file contents. This is my code:
here is the arraylist class
public class Customers implements Serializable{
ArrayList<Customer> customers = new ArrayList();
ArrayList<Customer> customers2 = new ArrayList();
public void add(Customer customerIn) {
customers.add(customerIn);
}
public void remove(Customer customerIn) {
customers.remove(customerIn);
}
public Customer findByName(String firstName, String address) {
//För varje Customer i customers
for (Customer customer : customers) {
if (firstName.equals(customer.getName())) {
if (address.equals(customer.getAddress())) {
return customer;
}
}
}
return null;
}
class for seriallize and deserialize
public class file {
public void saveObjectsToFile(Customers customers) {
try{
FileOutputStream fos= new FileOutputStream("a.listFile");
ObjectOutputStream oos= new ObjectOutputStream(fos);
oos.writeObject(customers);
oos.close();
fos.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
public void takeOutObjectFromFile(Customers customers) {
try
{
FileInputStream fis = new FileInputStream("a.listFile");
ObjectInputStream ois = new ObjectInputStream(fis);
customers = (Customers) ois.readObject();
ois.close();
fis.close();
//
System.out.println(customers);
}catch(IOException ioe){
ioe.printStackTrace();
return;
}catch(ClassNotFoundException c){
System.out.println("Class not found");
c.printStackTrace();
return;
}
}
class for customer
//klass customer startar här.
public class Customer implements Serializable{
//Variabler int och String för kund id, namn, adress och telefon.
int CustomerID;
String customerName, customerAddress, customerPhone, Order;
//Konstruktor för klassen
public Customer(String Name, String Address, String Phone, String Order) {
this.customerName = Name;
this.customerAddress = Address;
this.customerPhone = Phone;
this.CustomerID = 100001;
this.Order = Order;
}
//Hämtar och sätter personuppgifter.
public String getName() { return this.customerName; }
public String getAddress() { return this.customerAddress; }
public String getPhone() { return this.customerPhone; }
public int getID() { return this.CustomerID; }
public String getOrder() { return this.Order; }
//Skriver ut kontroll av personuppgifter.
public void printPerson() {
System.out.println("\n\nKONTROLL AV UPPGIFTER\n");
System.out.println("Namn:\t\t\t" + getName());
System.out.println("Adress:\t\t\t" + getAddress());
System.out.println("Telefonnummer:\t\t" + getPhone());
System.out.println("KundID:\t\t\t" + getID());
System.out.println("Order:\t\t\t" + getOrder());
}
public String toString() {
return getName() + " " + getAddress() + " " + getPhone();
}
}
The problem is with this method:
public void takeOutObjectFromFile(Customers customers) {
...
customers = (Customers) ois.readObject();
...
}
You've simply overwritten a local variable. What you should have is:
public Customers takeOutObjectFromFile() {
...
return (Customers) ois.readObject();
...
}
(Also use try-with-resource to ensure you have closed the files in all cases.)
I solved my problem!
Now i can edit my Customers! Thanks for all the help and advice.
public class file {
// Get all persons in file
public List<Customers> getAllPersons(String fileLocation) {
List<Customers> localPersons = new ArrayList<>();
try {
File f = new File(fileLocation);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
while (true) {
localPersons.add((Customers) ois.readObject());
}
} catch (EOFException e) {
}
} catch (IOException iOException) {
} catch (ClassNotFoundException classNotFoundException) {
}
return localPersons;
}
// Get person on personId in file
public Customers getPersonOnPersonId(String fileLocation, int personId) {
Customers localPerson = null;
try {
File f = new File(fileLocation);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
while (true) {
Customers tempPerson = (Customers) ois.readObject();
if(personId == tempPerson.getPersonId()) {
localPerson = tempPerson;
break;
}
}
} catch (EOFException e) {
}
} catch (IOException iOException) {
} catch (ClassNotFoundException classNotFoundException) {
}
return localPerson;
}
// Get persons on firstname in file
public List<Customers> getPersonsOnFirstName(String fileLocation, String firstName) {
List<Customers> localPersons = new ArrayList<>();
try {
File f = new File(fileLocation);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
while (true) {
Customers tempPerson = (Customers) ois.readObject();
if(firstName.equals(tempPerson.getFirstName())) {
localPersons.add(tempPerson);
}
}
} catch (EOFException e) {
}
} catch (IOException iOException) {
} catch (ClassNotFoundException classNotFoundException) {
}
return localPersons;
}
// Get persons on lastname in file
public List<Customers> getPersonsOnLastName(String fileLocation, String lastName) {
List<Customers> localPersons = new ArrayList<>();
try {
File f = new File(fileLocation);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
while (true) {
Customers tempPerson = (Customers) ois.readObject();
if(lastName.equals(tempPerson.getLastName())) {
localPersons.add(tempPerson);
}
}
} catch (EOFException e) {
}
} catch (IOException iOException) {
} catch (ClassNotFoundException classNotFoundException) {
}
return localPersons;
}
// Insert person in file
public void insertPerson(String fileLocation, Customers person) {
List<Customers> localPersons = new ArrayList<>();
// Select block ************************************************
int maxPersonId = 0;
try {
File f = new File(fileLocation);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
while (true) {
Customers tempPerson = (Customers) ois.readObject();
localPersons.add(tempPerson);
if(maxPersonId < tempPerson.getPersonId()) {
maxPersonId = tempPerson.getPersonId();
}
}
} catch (EOFException e) {
}
} catch (IOException iOException) {
} catch (ClassNotFoundException classNotFoundException) {
}
// *************************************************************
// Set primary key value to the person block *******************
if(localPersons.isEmpty()) {
person.setPersonId(1);
} else {
maxPersonId++;
person.setPersonId(maxPersonId);
}
// *************************************************************
// Insert block ************************************************
try {
File f = new File(fileLocation);
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
localPersons.add(person);
for(Customers p : localPersons) {
oos.writeObject(p);
}
} catch (FileNotFoundException fileNotFoundException) {
System.out.println(fileNotFoundException.getMessage());
} catch (IOException ioexception) {
System.out.println(ioexception.getMessage());
}
// *************************************************************
}
// Update person in file
public void updatePerson(String fileLocation, Customers person) {
List<Customers> localPersons = new ArrayList<>();
// Select block ************************************************
try {
File f = new File(fileLocation);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
while (true) {
Customers tempPerson = (Customers) ois.readObject();
if(person.getPersonId() != tempPerson.getPersonId()) {
localPersons.add(tempPerson);
} else {
localPersons.add(person);
}
}
} catch (EOFException e) {
}
} catch (IOException iOException) {
} catch (ClassNotFoundException classNotFoundException) {
}
// *************************************************************
// Insert block ************************************************
try {
File f = new File(fileLocation);
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
for(Customers p : localPersons) {
oos.writeObject(p);
}
} catch (FileNotFoundException fileNotFoundException) {
System.out.println(fileNotFoundException.getMessage());
} catch (IOException ioexception) {
System.out.println(ioexception.getMessage());
}
// *************************************************************
}
// Delete person in file
public void deletePerson(String fileLocation, int personId) {
List<Customers> localPersons = new ArrayList<>();
// Select block ************************************************
try {
File f = new File(fileLocation);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
while (true) {
Customers tempPerson = (Customers) ois.readObject();
if(personId != tempPerson.getPersonId()) {
localPersons.add(tempPerson);
}
}
} catch (EOFException e) {
}
} catch (IOException iOException) {
} catch (ClassNotFoundException classNotFoundException) {
}
// *************************************************************
// Insert block ************************************************
try {
File f = new File(fileLocation);
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
for(Customers p : localPersons) {
oos.writeObject(p);
}
} catch (FileNotFoundException fileNotFoundException) {
System.out.println(fileNotFoundException.getMessage());
} catch (IOException ioexception) {
System.out.println(ioexception.getMessage());
}
// *************************************************************
}
}
This is because your arralylist is being initialized again
change it to private static final this will make your day
private static final ArrayList<Customer> customers = new ArrayList();

Java program to read objects from a .ser file located in a server

My idea is that I want to read an object from a serialized file located in a server. How to do that?
I can only read .txt file using the following code :
void getInfo() {
try {
URL url;
URLConnection urlConn;
DataInputStream dis;
url = new URL("http://localhost/Test.txt");
// Note: a more portable URL:
//url = new URL(getCodeBase().toString() + "/ToDoList/ToDoList.txt");
urlConn = url.openConnection();
urlConn.setDoInput(true);
urlConn.setUseCaches(false);
dis = new DataInputStream(urlConn.getInputStream());
String s;
while ((s = dis.readLine()) != null) {
System.out.println(s);
}
dis.close();
} catch (MalformedURLException mue) {
System.out.println("Error!!!");
} catch (IOException ioe) {
System.out.println("Error!!!");
}
}
You can do this with this method
public Object deserialize(InputStream is) {
ObjectInputStream in;
Object obj;
try {
in = new ObjectInputStream(is);
obj = in.readObject();
in.close();
return obj;
}
catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
feed it with urlConn.getInputStream() and you'll get the Object. DataInputStream is not fit to read serialized objets that are done with ObjectOutputStream. Use ObjectInputStream respectively.
To write an object to the file there's another method
public void serialize(Object obj, String fileName) {
FileOutputStream fos;
ObjectOutputStream out;
try {
fos = new FileOutputStream(fileName);
out = new ObjectOutputStream(fos);
out.writeObject(obj);
out.close();
}
catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}

Categories

Resources