Using same writeToFile to write different arraylists in java - java

I have certain arraylists in my programm which I would like to write into a file so I can read them when starting the programm for a second time.
Currently it works for an arraylist of persons.
The reading part:
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("test.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
team.setPersonList((ArrayList<Person>) ois.readObject());
The writeToFile class:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class WriteToFile {
public void write(ArrayList<Person> Data ) throws IOException, ClassNotFoundException{
// create a new file with an ObjectOutputStream
FileOutputStream out = new FileOutputStream("test.txt");
ObjectOutputStream oout = new ObjectOutputStream(out);
// write something in the file
oout.writeObject(Data);
// close the stream
oout.close();
// create an ObjectInputStream for the file we created before
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("test.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// read and print what we wrote before
System.out.println("" + ois.readObject());
ois.close();
}
}
In main:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws ClassNotFoundException, IOException{
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
Team team = new Team(scan);
new InlogSystem(team, scan);
ArrayList<Person> playersData = team.getPersonList();
WriteToFile x = new WriteToFile();
x.write(playersData);
scan.close();
}
}
So this is the working part,
Now i want an arraylist of Strings to write into another txt file (not test like the personlist) using the same writeToFile class.
Obviously the writemethod only works for an arraylist of type person, and it always saves the array into "test.txt".
How do I write this arraylist without making a new method and having alot of ambigious code?
Thanks alot!

You can change the parameter type ArrayList<String> to ArrayList<?> or even List<?> or, what I would suggest, to Object. Then, your method is capable of writing arbitrary objects.
Using generics is useless here: It provides compile-time type checking, which wouldn't be used in your method.
By the way, your exception handling is very bad. I suggest you catch and re-throw the ClassNotFoundException as an IOException; FileNotFoundException is just a subclass of IOException and needn't be catched seperately - and why do you catch an IOException at all when your method is declared as throws IOException ?

Amend your method to accept List instead, where T is parametrized object. Refer to generics documentation

Use a generic method and pass the filename as a parameter i.e.
public <T implements Serializable> void write(ArrayList<T> Data, String filename) throws IOException {
// create a new file with an ObjectOutputStream
FileOutputStream out = new FileOutputStream(filename);
ObjectOutputStream oout = new ObjectOutputStream(out);
// write something in the file
oout.writeObject(Data);
// close the stream
oout.close();
// create an ObjectInputStream for the file we created before
ObjectInputStream ois = null;
ois = new ObjectInputStream(new FileInputStream("test.txt"));
// read and print what we wrote before
System.out.println("" + ois.readObject());
ois.close();
}

Related

Updating serialzed ArrayList in java

I am making a project where I need to save data to binary file using serilazation. I know how to read and write parameterized ArrayList using ObjectInputStream, ObjectOutputStream and FileInputStream. However I have no idea how I would go about updating ArrayList when new value is added or deleted.
import java.io.*;
import java.util.ArrayList;
public class testSerialization {
public static void main(String[] args){
String fileName = "test.bin";
ArrayList<Integer> integers = new ArrayList<>();
// Insert sample data
for (int i=0; i<10; i++){
integers.add(i);
}
try{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName));
oos.writeObject(integers);
oos.flush();
oos.close();
}catch(Exception e){
System.out.println(e);
}
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));
ArrayList<Integer> ps = (ArrayList<Integer>) ois.readObject();
System.out.println(ps);
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
One way I can do it is that I just override all the data with updated data everytime I get a change, but there is probably better alternative solution

Writing a file to java without erasing what's previously written in said file

I want to write a program that keeps what I've written in my file previously, and continually adds to it, instead of erasing it all every time I run the program.
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.lang.Math;
class Movie_Ratings_2 {
public static void main(String[] args) {
Scanner n = new Scanner (System.in);
String fileName = "output.txt";
String x = n.nextLine();
try {
PrintWriter outputStream = new PrintWriter(fileName);
outputStream.println(x);
outputStream.close();
outputStream.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

PrinterWriter creates a file but does not write to it. Tried flush and close everywhere. Still, does not write to file

Tried to put flush and close everywhere. Still, does not write to file. Changed file location, path of the file, still does not write to the file; however it creates it.
public void filePatient(HashMap<Integer,Patient> collection, String filename) {
// crating a file
File file = new File (filename+".txt");
try (PrintWriter out = new PrintWriter(new FileWriter(file),true)) {
for(Patient i: collection.values()) {
out.write(i.getName());
//out.write(i.getHealthNumber());
}
out.flush();
out.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Your code works as-is.
You can also remove the close, as you use try-with-resources.
Here's a full working example:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("a", "my name");
map.put("b", "your name");
filePatient(map, "c:\\temp\\test");
}
public static void filePatient(Map<String, String> collection, String filename) {
// crating a file
File file = new File(filename + ".txt");
try (PrintWriter out = new PrintWriter(new FileWriter(file), true)) {
for (String name : collection.values()) {
out.write(name);
}
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

JAVA - Writing sentences to textfile

I have this code below. Basically I'm getting an input from a given url. This website shows a sentence. Each time I reload the website it gets a new sentence and so on. So, I managed to get that working. Now I'm trying to write the sentence in a textfile. But something is wrong. It only writes the first line and nothing else. What's wrong with my code?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class ReadIp {
public static void main(String[] args) throws MalformedURLException, IOException,
InterruptedException {
ReadIp readIP = new ReadIp();
while (true) {
readIP.getIP();
Thread.sleep(2000);
}
}
BufferedReader buff;
InputStreamReader inStream;
String line;
URL url;
URLConnection urlConn;
FileWriter fileWriter ;
BufferedWriter bufferedWriter;
public ReadIp() throws IOException {
fileWriter = new FileWriter("myfile.txt", true);
bufferedWriter = new BufferedWriter(fileWriter);
}
public void getIP() throws MalformedURLException, IOException {
this.url = new URL("http://test.myrywebsite.co.uk");
this.urlConn = this.url.openConnection();
this.inStream = new InputStreamReader(this.urlConn.getInputStream());
this.buff = new BufferedReader(this.inStream);
try {
while ((this.line = this.buff.readLine()) != null)
{
System.out.println(this.line);
try {
this.bufferedWriter.write(this.line);
this.bufferedWriter.write("\n");
this.bufferedWriter.flush();
} catch (IOException e)
{
}
}
if (this.bufferedWriter != null)
{
this.bufferedWriter.close();
}
this.inStream.close();
}
catch (Exception ex)
{
}
}
}
Any help would be greatly appreciated.
Thank you.
Move the statement
writer.close();
out of the inner try catch block so that you're not closing the OutputStream after writing the first entry to the file. The same applys to the InputStream
inStream.close();
The BufferedWriter is being opened in the constructor and is being closed in getIp. The constructor is called only once, but getIp is called every 2 seconds to read a sentence. So the BufferedWriter is being closed after the first line (and not opened again). The second call of getIp tries to write the second sentence but the BufferedWriter is closed. This should throw an Exception which is being ignored since the catch block is empty.
Never leave a catch block empty - as fgb wrote above!
First of all, at least add a printStackTrace() to each empty catch block, e.g.:
catch (Exception ex) {
ex.printStackTrace();
}
so you can see if an Exception is being thrown...
I would suggest to open the BufferedWriter in the method getIp instead of the constructor; or, if it should stay open all the time, close the BufferedWriter in an additional method, called after the loop in main terminates

Reading serialised object java gives classnotfound exception

Here's my current code:
//export method
public static void exportObj (Object obj, String fname) {
try {
// Serialize data object to a file
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fname));
out.writeObject(obj);
out.close();
} catch (IOException e) {}
}
//import method
public static Object importObj (String fname) {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(fname));
return in.readObject();
} catch (IOException e) {}
return new Object();
}
The export function works fine, I think, it turns my User object into a file and saves it, but then when I try to import it, it gives me a ClassNotFound Exception. What is happening?
All the classes you want to deserialize must exist on the CLASSPATH of the project that contains the import code.

Categories