0

I need to write a class that has two static methods: writeFile and readFile. However, after I do my readFile(), it returns nothing.

class writereadFile {
    public static void writeFile(ArrayList<Object> list, File file){
        try {
            try (FileOutputStream fos = new FileOutputStream(file);ObjectOutputStream oos = new ObjectOutputStream(fos)) {
                oos.writeObject(list);
                oos.close();
            }
        }catch(IOException e){e.getMessage();}
    }

    public static ArrayList<Object> readFile(ArrayList<Object>list, File file){
        try {
            try (FileInputStream fis = new FileInputStream(file);ObjectInputStream ois = new ObjectInputStream(fis)) {
                Object o = ois.readObject();
                list = (ArrayList<Object>) o;
                ois.close();
            }
        }catch(IOException | ClassNotFoundException e){e.getMessage();}  
        System.out.println(list);
        return list;
    } 
}

EDIT: This my class for testing. My object is an arraylist of custom objects if you need the custom object just comment.

class main {
    public static void main(String[] args) {
        Date date = new Date();
        Book b1 = new Book("abc", "Phi", true, date, null);
        Book b2 = new Book("cba", "Someone", true, date, null);
        Books booklist = new Books();
        booklist.add(b1);
        booklist.add(b2);

        File filetoDo = new File("book.txt");

        //write arraylist into file
        writereadFile.writeFile(booklist, filetoDo);

        //clear the arraylist
        booklist.clear();

        //read book from file
        writereadFile.readFile(booklist, filetoDo);
        System.out.println(booklist);
    }    
} 
1
  • 1
    Probably a good idea to print the exception in your writeFile method. Commented May 13, 2017 at 17:28

3 Answers 3

1

Your test should read:

bookList = writereadFile.readFile(booklist, filetoDo);

and, by the way, you should really refactor your readFile method to simply:

public static ArrayList<Object> readFile(File file)

You can't modify the argument reference like that, since Java is always pass-by-value call semantics. (You could modify the list argument contents inside the function, but that's not what you are doing.)

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, this one works, I misunderstood pass and return
@PhiTruong Be sure to mark it as the accepted answer when you get a chance... thanks man! :)
Sorry, I'm newish :)
0

If you are using Java 8 try using Streams:

public static readFile(String filePath) {
    List<Object> list = new ArrayList<>();

    try (Stream<String> stream = Files.lines(Paths.get(filePath))) {
        stream.forEach(list::add);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return list;
}

1 Comment

that's nice and dandy for text files, but OP is dealing with objects and serialization
0

I'm playing around this topic a bit on my own, so below you can find some code snippets that might help you. Examples are very short and simple, so I hope you will not just use e.printStackTrace() in your code :)

public class ExternalIO {

private ExternalIO() {
}

public static ObjectOutputStream objectOutputStream(String basePath, String pathToFile) throws IOException {
    FileOutputStream fileOutputStream = new FileOutputStream(createFileIfDoesNotExist(absolutePath(basePath, pathToFile)));
    return new ObjectOutputStream(fileOutputStream);
}

public static ObjectInputStream objectInputStream(String basePath, String pathToFile) throws IOException {
    FileInputStream fileInputStream = new FileInputStream(absolutePath(basePath, pathToFile));
    return new ObjectInputStream(fileInputStream);
}

private static File createFileIfDoesNotExist(String absolutePath) throws IOException {
    File file = new File(absolutePath);
    if (file.exists()) {
        return file;
    }

    file.getParentFile().mkdirs();
    file.createNewFile();
    return file;
}

private static String absolutePath(String basePath, String pathToFile) {
    return Paths.get(basePath, pathToFile).toAbsolutePath().toString();
}

}

output usage:

List<ItemType> input = null; //create your input list here
try (ObjectOutputStream objectOutputStream = ExternalIO.objectOutputStream(CONFIG, FILENAME)) {
    objectOutputStream.writeObject(input);
} catch (Exception e) {
    e.printStackTrace();
}

input usage:

try (ObjectInputStream objectInputStream = ExternalIO.objectInputStream(CONFIG, FILENAME)) {
    return (List<ItemType>) objectInputStream.readObject();
} catch (Exception e) {
    e.printStackTrace();
}

hope that helps ; )

2 Comments

Could you go more detailed about absolutePath()?
well... it just returns an absolute path to the file, instead of using a relative one. then again, you may just get rid of this, because it does not change anything for your usage probably. I just pasted it there to be sure that code compiles :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.