Phi Truong
Phi Truong

Reputation: 111

Java read a file into an arraylist of objects and return that arraylist

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);
    }    
} 

Upvotes: 0

Views: 2440

Answers (3)

Paulo Mattos
Paulo Mattos

Reputation: 19339

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.)

Upvotes: 1

WrRaThY
WrRaThY

Reputation: 1998

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 ; )

Upvotes: 0

nick79
nick79

Reputation: 427

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;
}

Upvotes: 0

Related Questions