1 package org.thegalactic.io;
2
3 /*
4 * Filer.java
5 *
6 * Copyright: 2010-2015 Karell Bertet, France
7 * Copyright: 2015-2016 The Galactic Organization, France
8 *
9 * License: http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html CeCILL-B license
10 *
11 * This file is part of java-lattices.
12 * You can redistribute it and/or modify it under the terms of the CeCILL-B license.
13 */
14 import java.io.BufferedReader;
15 import java.io.BufferedWriter;
16 import java.io.FileReader;
17 import java.io.FileWriter;
18 import java.io.IOException;
19
20 /**
21 * This class is used to provide a generic way for saving and parsing objects
22 * using the extension file.
23 *
24 * @param <E> The element to be saved/parsed
25 */
26 public final class Filer<E> {
27
28 /**
29 * The singleton instance.
30 */
31 private static final Filer INSTANCE = new Filer();
32
33 /**
34 * Return the singleton instance of this class.
35 *
36 * @return the singleton instance
37 */
38 public static Filer getInstance() {
39 return INSTANCE;
40 }
41
42 /**
43 * Get the filename extension.
44 *
45 * @param filename Filename to get extension from
46 *
47 * @return the filename extension
48 */
49 private static String getExtension(final String filename) {
50 String extension = "";
51 final int index = filename.lastIndexOf('.');
52 if (index > 0) {
53 extension = filename.substring(index + 1);
54 }
55 return extension;
56 }
57
58 /**
59 * This class is not designed to be publicly instantiated.
60 */
61 private Filer() {
62 }
63
64 /**
65 * Save the description of this component in a file whose name is specified.
66 *
67 * @param e the element to save
68 * @param factory the reader/writer factory
69 * @param filename the name of the file
70 *
71 * @throws IOException When an IOException occurs
72 */
73 public void save(final E e, final IOFactory factory, final String filename) throws IOException {
74 final BufferedWriter file = new BufferedWriter(new FileWriter(filename));
75 factory.getWriter(Filer.getExtension(filename)).write(e, file);
76 file.close();
77 }
78
79 /**
80 * Parse the description of this component from a file whose name is
81 * specified.
82 *
83 * @param e the element to parse
84 * @param factory the reader/writer factory
85 * @param filename the name of the file
86 *
87 * @throws IOException When an IOException occurs
88 */
89 public void parse(final E e, final IOFactory factory, final String filename) throws IOException {
90 final BufferedReader file = new BufferedReader(new FileReader(filename));
91 factory.getReader(Filer.getExtension(filename)).read(e, file);
92 file.close();
93 }
94 }