How to serialize an object using JFileChooser - java

I want to use the JFileChooser to create a dialog box to save my 2 by 2 Array as a serialized object.
This is the code I have used previously to serialize objects and it works fine however, this just generates the file and puts it in the same directory as the program. I want to use the JFileChooser to choose the location of the saved file.
private void serializeMap() throws IOException {
File file = new File("map.txt");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(grid);
oos.close();
}
So far this is all I have.
private void exportMap() {
KeyboardFocusManager.setCurrentKeyboardFocusManager(new DefaultKeyboardFocusManager());
JFileChooser fileChooser = new JFileChooser();
fileChooser.setSelectedFile(new File("map.txt"));
fileChooser.showSaveDialog(this);
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(gameKeys);
}

Related

Java: How to convert com.google.api.services.drive.model.File to InputStream?

I am new to google drive integration.
I saved an image in google drive and I got that file by below method.
File file = getDriveService().files().get(fileId).execute();
Now when I tried to convert this file into InputStream and write this InputStream in HttpResponse then the file returns but the image is not displayed.
public InputStream convertGoolgeFileToInputStream( String fileId ) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
getDriveService().files().get(fileId).executeAndDownloadTo(outputStream);
InputStream in = new ByteArrayInputStream(outputStream.toByteArray());
return in;
//return getDriveService().files().get(fileId).executeAsInputStream();
}
You may want to try checking the download example Drive sample
private static void downloadFile(boolean useDirectDownload, File uploadedFile)
throws IOException {
// create parent directory (if necessary)
java.io.File parentDir = new java.io.File(DIR_FOR_DOWNLOADS);
if (!parentDir.exists() && !parentDir.mkdirs()) {
throw new IOException("Unable to create parent directory");
}
OutputStream out = new FileOutputStream(new java.io.File(parentDir, uploadedFile.getTitle()));
MediaHttpDownloader downloader =
new MediaHttpDownloader(httpTransport, drive.getRequestFactory().getInitializer());
downloader.setDirectDownloadEnabled(useDirectDownload);
downloader.setProgressListener(new FileDownloadProgressListener());
downloader.download(new GenericUrl(uploadedFile.getDownloadUrl()), out);
}

Java Cant read or write object to file

There is this method klasOpslaan(Klas deKlas). I need to write deKlas to an object. Afterwards I need to read it with method klasInladen. I am getting an error writing aborted; java.io.NotSerializableException: week5.practicum4.Klas although I implemented Serializeable. I did note that when writing my object it makes the object but doesn't write to it. I did implement everything but StackOverflow wont let me post it.
public class KlasManager implements Serializable {
public void klasOpslaan(Klas deKlas) throws IOException, FileNotFoundException {
FileOutputStream fos = new FileOutputStream("C:\\Users\\Sam\\Documents\\Java School\\klas.obj");
ObjectOutputStream oos = new ObjectOutputStream(fos);
System.out.println("Klas opgeslassgen");
oos.writeObject(deKlas);
oos.close();
}
public Klas klasInladen() throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream("C:\\Users\\Sam\\Documents\\Java School\\klas.obj");
ObjectInputStream ois = new ObjectInputStream(fis);
Klas deKlas = (Klas) ois.readObject();
ois.close();
return deKlas;
}
}
edit: needed Serializeable in other classes, not in this one.

Error while trying to read an Excel file

When I run the code below:
Properties p = new Properties();
public Properties getObjectRepository() throws IOException{
//Read object repository file
InputStream stream = new FileInputStream(new File(System.getProperty("D:\\src\\objects\\object.properties")));
//load all objects
p.load(stream);
return p;
}
It shows error as:
Exception in thread "main" java.lang.NullPointerException
at java.io.File.<init>(Unknown Source)
at uioperation.Excel_object.getObjectRepository(Excel_object.java:14)
at ExecuteTestcase.Testcase_execute.main(Testcase_execute.java:27)
What is wrong with my code?
I do not believe that you have a System property called D:\\src\\objects\\object.properties
so
change to
new File("D:\\src\\objects\\object.properties"));
assuming that this file does exist
Seems your code for setting the property is not implemented, But you can simply Open a file using following code.
Properties p = new Properties();
public Properties getObjectRepository() throws IOException{
//Read object repository file
String FileName="Path to your file";
InputStream stream = new FileInputStream(new File(fileName));
//load all objects
p.load(stream);
return p;
}
Or otherwise, you should get it from system properties..
Properties p = new Properties();
public Properties getObjectRepository() throws IOException{
//Read object repository file
String FileName=System.getProperty("Prperty Key for your file path"); // the property should ave been already set somewhere in the code before execution of this line
InputStream stream = new FileInputStream(new File(fileName));
//load all objects
p.load(stream);
return p;
}
This is for setting the property and accessing the file
Properties p = new Properties();
public Properties getObjectRepository() throws IOException{
//Set Property for file path
setProperty("filePath","D:\\src\\objects\\object.properties");
//Read object repository file
String FileName=System.getProperty("filePath"); //now fileName is similar to "D:\\src\\objects\\object.properties"
InputStream stream = new FileInputStream(new File(fileName));
//load all objects
p.load(stream);
return p;
}

Convert Myobject to byte

I want to object AuditContainer convert to byte and then save in file:
public class AuditContainer implements Serializable {
private Paint mPaint;
private Path mPath;
private int x,y;
private String text;
boolean is_text;
Problem is because Paint and Path must be serialized, but it cant..
Firstly i want make serialization for this class, but i have got one truble, i cant save all things which i need.
My question is how i can convert AuditoContainer to byte? Is it Posible? and which is princips/options for save my class in file/database?
I need help, please.
If what you want is to write the status of the object to a file, is better if you don't use serialization. Serialization has lots of flaws and is hard to get it done correctly, while you can save the properties of your object easily as strings in the file.
want serialization example ?
ok here is one (make sure that all your Objects mentioned in your variables are serializable as well)
public void save(AuditContainer auditContainer, File file) throws FileNotFoundException, IOException {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try{
fos = new FileOutputStream(file);
oos = new ObjectOutputStream(fos);
oos.writeObject(auditContainer);
}finally{
if(oos != null){
oos.flush();
oos.close();
}
}
}
public AuditContainer load(File file) throws FileNotFoundException, IOException, ClassNotFoundException {
AuditContainer auditContainer = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try{
fis = new FileInputStream(file);
ois = new ObjectInputStream(ois);
auditContainer = (AuditContainer)ois.readObject();
}finally{
if(ois != null){
ois.close();
}
}
return auditContainer;
}

IOException at java.io.File.createNewFile();

I do have some code for serialization which does not work. I have tried to insert both CanRead() and CanWrite() in if-statements which showed they did not have permissions to read and write. I have also tried to insert 'java.io.File.setReadable' and 'java.io.File.setWriteable to true but it still throws the error.
The code is as following:
public static void save(Object obj, String filename) throws FileNotFoundException, IOException
{
File f = new File("c:/DatoChecker/" + filename);
File dir = new File("c:/DatoChecker");
if(!dir.exists())
dir.mkdirs();
f.setReadable(true);
f.setWritable(true);
if(!f.exists())
{
f.createNewFile();
}
FileOutputStream op = null;
ObjectOutputStream objectStream = null;
op = new FileOutputStream(f);
objectStream = new ObjectOutputStream(op);
objectStream.writeObject(obj);
objectStream.close();
}
public static Object fetch(String filename) throws FileNotFoundException, IOException, ClassNotFoundException
{
File f = new File("c:/DatoChecker" + filename);
File dir = new File("c:/DatoChecker");
if(!dir.exists())
dir.mkdirs();
f.setReadable(true);
f.setWritable(true);
if(!f.exists())
{
f.createNewFile();
}
FileInputStream ip = null;
ObjectInputStream objectStream = null;
Object obj = null;
ip = new FileInputStream(f);
objectStream = new ObjectInputStream(ip);
obj = objectStream.readObject();
ip.close();
objectStream.close();
return obj;
}
Stacktrace:
SEVERE: null
java.io.IOException: access denied
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:947)
at com.check.me.Serialization.fetch(Seralization.java:39)
at com.check.me.GoodsList.load(GoodsList.java:82)
at com.check.me.START.main(START.java:22)
The one for save is congruet from GoodsList (just save instead of load) and up but it is quite a bit longer below so I will leave it out for now.
Thanks for the help beforehand
Highace2
You state that you did not have permission to read or write. And, indeed, you get an error telling you that you don't have permission. You need to change the ACL on the directory in which you are creating the file, or pick a different directory.

Categories