I am trying to serialize the following class:
public class Library extends ArrayList<Book> implements Serializable{
public Library(){
check();
}
using the following method of that class:
void save() throws IOException {
String path = System.getProperty("user.home");
File f = new File(path + "\\Documents\\CardCat\\library.ser");
ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream (f));
oos.writeObject(this);
oos.close();
}
However, rather than creating a file called library.ser, the program is creating a directory named library.ser with nothing in it. Why is this?
If its helpful, the save() method is initially called from this method (of the same class):
void checkFile() {
String path = System.getProperty("user.home");
File f = new File(path + "\\Documents\\CardCat\\library.ser");
try {
if (f.exists()){
load(f);
}
else if (!f.exists()){
f.mkdirs();
save();
}
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(Library.class.getName()).log(Level.SEVERE, null, ex);
}
}
File.mkdirs() creating a directory instead of a file
That's what it's supposed to do. Read the Javadoc. Nothing there about creating a file.
f.mkdirs();
It is this line that creates the directory. It should be
f.getParentFile().mkdirs();
I'm pretty sure that the call to f.mkdirs() is your problem. If the file doesn't already exist (which seems to be your case), the f.mkdirs() call will give you a directory called "library.ser" instead of a File, which is why your "save()" call isn't working - you can't serialize an object to a directory.
Related
I have a Path variable like this:
Path output;
This path is initialized in the main-method.
I want to check if there exists a File in this path
and if thats the case- write a string into that file.
Else create a new File with the given path and write
the string.
//void parseOutput(String s){
//if (file in path exists)
// write(s in file from path)
else
File f = new File(String.valueOf(output));
write String in f
You can try this :
import java.io.*;
class FileDemo {
public static void main(String str[]) {
String path = "E:/myfile.txt";
File file = new File(path);
if(file.exists()) {
System.out.println("File is exist..!!!");
} else {
try {
FileWriter fileWriter = new FileWriter(path);
fileWriter.write("This is my first file..!!");
fileWriter.close();
System.out.println("File has some content..!!");
} catch(Exception exception) {
System.out.println(exception.getMessage());
}
}
}
}
If you have a Path, it doesn't really make sense to convert that to a String and use the File constructor.
For checking if a file exists, you can use Files exists.
To add to an existing file, have a look at Files.newBufferedWriter with the APPEND OpenOption set.
Full example:
Path path = Paths.get("/path/to/file.txt");
try (BufferedWriter bufferedWriter = Files.newBufferedWriter(
path, StandardOpenOption.APPEND, StandardOpenOption.CREATE);
PrintWriter printWriter = new PrintWriter(bufferedWriter))
{
printWriter.println("This is a line");
}
You might want to use exists() method in File class. Here's an example which you could use:
public void writeOnFile(String path, String str) throws FileNotFoundException {
PrintWriter out;
File file = new File(path);
if (file.exists()){
out = new PrintWriter(file.getPath());
out.println(str);
}
}
public class Inventory implements Serializable {
ArrayList<Product> productlist;
File file;
public Inventory(){
productlist = new ArrayList<Product>();
file = new File("build/classes/inventory/inv.ser");
if(!file.exists()){
try {
file.getParentFile().mkdirs();
file.createNewFile();
} catch (IOException ex) {
Logger.getLogger(Inventory.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(file.length() !=0){
loadFile(file);
}
}
public void addProduct(Product product){
productlist.add(product);
saveFile(this.file);
}
public void saveFile(File file){
try{
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(productlist);
out.close();
fos.close();
} catch(FileNotFoundException ex){System.out.println("FileNotFoundException");}
catch(IOException ex){System.out.println("InputException");}
}
public void loadFile(File file){
try{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fis);
productlist=(ArrayList<Product>)in.readObject();
in.close();
fis.close();
} catch(FileNotFoundException ex){ System.out.println("FileNotFoundException"); }
catch(IOException ex){System.out.println("OutputException");}
catch(ClassNotFoundException ex){System.out.println("ClassNotFoundException");}
}
}
Does writeObject() overwrite the content of the existing file or append the objects to the existing file?
And is it a good idea to serialize an ArrayList of Objects like what i did inside the saveFile method?
Does writeObject() overwrite the content of the existing file or append the objects to the existing file?
Neither. It writes the object to the underlying stream. The underlying stream is a serial byte stream that can only be appended to. In this case the underlying stream is backed by an underlying file, which has or has not already been overwritten, depending on how you constructed the FileOutputStream. It has nothing to do with writeObject(). In any case you can't successfully append to a file of serialized objects without taking special measures.
And is it a good idea to serialize an ArrayList of Objects like what i did inside the saveFile method?
Compared to what?
N.B.
When you get an exception, print it. Not just some message of your own devising.
Creating a file just so you can test it for zero length doesn't make sense.
The directory build/classes/inventory won't be there at runtime once you stop using the IDE. This is no place to put a file.
You could try FileUtils function to write list of object into plane text file.
Please find below URL for reference -
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#writeLines-java.io.File-java.util.Collection-java.lang.String-boolean-
e.g.
FileUtils.writeLines(new File(fileToAttach), list);
I'm trying to write a binary file to a specified folder, however it keeps giving me an exception.
For example, if I write the file without specifying any folder the program writes it with no problem:
public void saveFile(String name) throws IOException {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(name + ".bin"));
out.writeObject(this);
out.close();
}
However, when I try to specify the folder the program just doesn't write the file:
public void saveFile(String name) throws IOException {
File location = new File("/path/" + name + ".bin");
FileOutputStream fos = new FileOutputStream(location);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(this);
out.close();
fos.close();
}
I tryed several different ways but still no solution.
Does anybody know what am I doing wrong?
Check if the class which you want to write is Serializable or not.
public class Foo implements java.io.Serializable{
//...
public void write() throws IOException{
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("Test.bin"));
os.writeObject(this);
os.close();
}
}
Another problem:
If there is no folder named path it cannot write the object
Check your code again.
The Only reason seems for non Serialization is that u might not have implemented Serializable interface
and give your path name correctly for eg:-"C:\Users\.."
Hope it works
If I want to create a file in C:/a/b/test.txt, can I do something like:
File f = new File("C:/a/b/test.txt");
Also, I want to use FileOutputStream to create the file. So how would I do it? For some reason the file doesn't get created in the right directory.
The best way to do it is:
String path = "C:" + File.separator + "hello" + File.separator + "hi.txt";
// Use relative path for Unix systems
File f = new File(path);
f.getParentFile().mkdirs();
f.createNewFile();
You need to ensure that the parent directories exist before writing. You can do this by File#mkdirs().
File f = new File("C:/a/b/test.txt");
f.getParentFile().mkdirs();
// ...
With Java 7, you can use Path, Paths, and Files:
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateFile {
public static void main(String[] args) throws IOException {
Path path = Paths.get("/tmp/foo/bar.txt");
Files.createDirectories(path.getParent());
try {
Files.createFile(path);
} catch (FileAlreadyExistsException e) {
System.err.println("already exists: " + e.getMessage());
}
}
}
Use:
File f = new File("C:\\a\\b\\test.txt");
f.mkdirs();
f.createNewFile();
Notice I changed the forward slashes to double back slashes for paths in Windows File System. This will create an empty file on the given path.
String path = "C:"+File.separator+"hello";
String fname= path+File.separator+"abc.txt";
File f = new File(path);
File f1 = new File(fname);
f.mkdirs() ;
try {
f1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This should create a new file inside a directory
A better and simpler way to do that :
File f = new File("C:/a/b/test.txt");
if(!f.exists()){
f.createNewFile();
}
Source
Surprisingly, many of the answers don't give complete working code. Here it is:
public static void createFile(String fullPath) throws IOException {
File file = new File(fullPath);
file.getParentFile().mkdirs();
file.createNewFile();
}
public static void main(String [] args) throws Exception {
String path = "C:/donkey/bray.txt";
createFile(path);
}
Create New File in Specified Path
import java.io.File;
import java.io.IOException;
public class CreateNewFile {
public static void main(String[] args) {
try {
File file = new File("d:/sampleFile.txt");
if(file.createNewFile())
System.out.println("File creation successfull");
else
System.out.println("Error while creating File, file already exists in specified path");
}
catch(IOException io) {
io.printStackTrace();
}
}
}
Program Output:
File creation successfull
To create a file and write some string there:
BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get("Path to your file"));
bufferedWriter.write("Some string"); // to write some data
// bufferedWriter.write(""); // for empty file
bufferedWriter.close();
This works for Mac and PC.
For using the FileOutputStream try this :
public class Main01{
public static void main(String[] args) throws FileNotFoundException{
FileOutputStream f = new FileOutputStream("file.txt");
PrintStream p = new PrintStream(f);
p.println("George.........");
p.println("Alain..........");
p.println("Gerard.........");
p.close();
f.close();
}
}
When you write to the file via file output stream, the file will be created automatically. but make sure all necessary directories ( folders) are created.
String absolutePath = ...
try{
File file = new File(absolutePath);
file.mkdirs() ;
//all parent folders are created
//now the file will be created when you start writing to it via FileOutputStream.
}catch (Exception e){
System.out.println("Error : "+ e.getmessage());
}
I have a config.properties file at the root of my blackberry project (same place as Blackberry_App_Descriptor.xml file), and I try to access the file to read and write into it.
See below my class:
public class Configuration {
private String file;
private String fileName;
public Configuration(String pathToFile) {
this.fileName = pathToFile;
try {
// Try to load the file and read it
System.out.println("---------- Start to read the file");
file = readFile(fileName);
System.out.println("---------- Property file:");
System.out.println(file);
} catch (Exception e) {
System.out.println("---------- Error reading file");
System.out.println(e.getMessage());
}
}
/**
* Read a file and return it in a String
* #param fName
* #return
*/
private String readFile(String fName) {
String properties = null;
try {
System.out.println("---------- Opening the file");
//to actually retrieve the resource prefix the name of the file with a "/"
InputStream is = this.getClass().getResourceAsStream(fName);
//we now have an input stream. Create a reader and read out
//each character in the stream.
System.out.println("---------- Input stream");
InputStreamReader isr = new InputStreamReader(is);
char c;
System.out.println("---------- Append string now");
while ((c = (char)isr.read()) != -1) {
properties += c;
}
} catch (Exception e) {
}
return properties;
}
}
I call my class constructor like this:
Configuration config = new Configuration("/config.properties");
So in my class, "file" should have all the content of the config.properties file, and the fileName should have this value "/config.properties".
But the "name" is null because the file cannot be found...
I know this is the path of the file which should be different, but I don't know what i can change... The class is in the package com.mycompany.blackberry.utils
Thank you!
I think you need to put the config.properties file into a source folder when you build the project, you can create a "resources" folder as a src folder and put the config file in it, than you can get the file in the app
Try putting the file in the same package as the class?
Class clazz = Class.forName("Configuration");
InputStream is = addFile.getResourceAsStream(fName);