Im having problems writing/reading object as resources on file.
I run code from the Main.java
Class, and I want to write/read an object to the users.txt
file.
The object that I want to write/read is the TryStructure
Object, which just incapsulates a 1 element array and implements the Serializable interface, needed for object writing.
package Main;
import java.io.Serializable;
import java.util.ArrayList;
public class TryStructure implements Serializable
{
private static final long serialVersionUID = 1L;
private ArrayList<Integer> a = new ArrayList<Integer>();
public TryStructure()
{
a.add(5);
}
public String getStructure()
{
return a.toString();
}
}
The Main.java
class writes and reads the obj from the users.txt
file.
package Main;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URISyntaxException;
import java.net.URL;
public class Main
{
public static void main(String[] args)
{
String res = "/res/users.txt";
write(res);
read(res);
}
private static void write(String resName)
{
TryStructure list = new TryStructure();
FileOutputStream fos;
ObjectOutputStream oos;
URL resource = Main.class.getClass().getResource(resName);
File file = null;
try
{
file = new File(resource.toURI());
fos = new FileOutputStream(file);
oos = new ObjectOutputStream(fos);
System.out.println("WRITING: " + list.getStructure());
oos.writeObject(list);
oos.close();
fos.close();
}
catch (IOException e)
{
System.err.println("users.txt not found !");
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
}
private static void read(String resName)
{
FileInputStream fos;
ObjectInputStream oos;
URL resource = Main.class.getClass().getResource(resName);
File file = null;
try
{
file = new File(resource.toURI());
fos = new FileInputStream(file);
oos = new ObjectInputStream(fos);
System.out.println("READING: " + ((TryStructure) oos.readObject()).getStructure());
oos.close();
fos.close();
}
catch (IOException e)
{
System.err.println("users.txt not found !");
}
catch (ClassNotFoundException e)
{
System.out.println("AA");
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
}
}
If I run the code I get the following output:
WRITING: [5]
READING: [5]
If I then check the user.txt file I find it empty, and I find the information in bin/res/user.txt
.
I dont understand why it only updates the file in bin folder and not also the one in res folder, why is this happening? I would like to write to that specific file.
Thank you.