Java - Necesito ayuda para resolver un programa

 
Vista:

Necesito ayuda para resolver un programa

Publicado por Israel (1 intervención) el 11/05/2019 05:03:18
El programa consiste en tomar realizar una interfaz grafica donde seleccione un archivo de tipo CSV, JSON o XML y convertirlo cualquiera de esos archivos a el formato de los otros dos restantes, por ejemplo seleccionar un CSV y convertirlo a JSON o XML, tambien con los datos de ese archivo se debe crear una tabla con las dimensiones segun los datos de archivo
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Billy Joel
Val: 2.665
Oro
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

Necesito ayuda para resolver un programa

Publicado por Billy Joel (875 intervenciones) el 13/05/2019 19:53:05
Antes de empezar, te recomiendo descargar la librería JSON-java
http://www.json.org/
5bd9b9a8ef5ec-json_org

Lo metes en un paquete para que te quede así:
5bd9b9d094d51-json-package

La parte gráfica te la dejo a ti...

Vayamos a lo espeso del asunto... Manejo de archivos CSV, XML y JSON
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Billy Joel
Val: 2.665
Oro
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

Necesito ayuda para resolver un programa

Publicado por Billy Joel (875 intervenciones) el 13/05/2019 19:53:46
La parte gráfica te la dejo a ti...

Vayamos a lo espeso del asunto... Manejo de archivos CSV, XML y JSON

Esto te resuelvo así:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
 
/**
 *
 * @author billy.johnson
 */
public class Archivos {
 
    public File readFile(File a, TipoArchivo tipoLectura, TipoArchivo tipoSalida) {
        JSONObject o;
        if (null == tipoLectura) {
            o = null;
        } else {
            switch (tipoLectura) {
                case CSV:
                    o = readCSV(a);
                    break;
                case XML:
                    o = readXML(a);
                    break;
                case JSON:
                    o = readJSON(a);
                    break;
                default:
                    o = null;
                    break;
            }
        }
        File f;
        if (null == tipoSalida) {
            f = null;
        } else {
            switch (tipoSalida) {
                case CSV:
                    if (o == null) {
                        f = null;
                    } else {
                        f = writeCSV(a.getName()
                                .substring(0, a.getName().lastIndexOf(".")) + ".csv",
                                (String[]) o.get("columns"),
                                (List<String[]>) o.get("rows"));
                    }
                    break;
                case XML:
                    f = writeXML(a.getName()
                            .substring(0, a.getName().lastIndexOf(".")) + ".xml",
                            o);
                    break;
                case JSON:
                    f = writeJSON(a.getName()
                            .substring(0, a.getName().lastIndexOf(".")) + ".xml",
                            o);
                    break;
                default:
                    f = null;
                    break;
            }
        }
        return f;
    }
 
    /**
     * Lee un archivo CSV y devuelve un Map con 2 valores
     * <ul>
     * <li><b>columns</b> String [] con los nombres de las columnas</li>
     * <li><b>rows</b> List&lt;String []&gt; con los registros del archivo</li>
     *
     * </ul>
     *
     * @param a
     * @return
     */
    public JSONObject readCSV(File a) {
        Map<String, Object> m = new HashMap();
        try {
            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                            new FileInputStream(a), "UTF8"))) {
                String line;
                boolean primeraFila = true;
                List<String[]> rows = new ArrayList();
                while ((line = in.readLine()) != null) {
                    if (primeraFila) {
                        m.put("columns", line.split(";"));
                        primeraFila = false;
                    } else {
                        rows.add(line.split(";"));
                    }
                }
                m.put("rows", rows);
            }
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return new JSONObject(m);
    }
 
    /**
     * Lee un archivo en formato JSON
     *
     * @param a
     * @return
     */
    public JSONObject readJSON(File a) {
        String body = "";
        try {
            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                            new FileInputStream(a), "UTF8"))) {
                String line;
 
                while ((line = in.readLine()) != null) {
                    body += line;
                }
            }
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        JSONObject o = null;
        if (!body.isEmpty()) {
            try {
                o = new JSONObject(body);
            } catch (JSONException ex) {
                ex.printStackTrace(System.out);
            }
        }
        return o;
    }
 
    public JSONObject readXML(File a) {
        String body = "";
        try {
            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                            new FileInputStream(a), "UTF8"))) {
                String line;
 
                while ((line = in.readLine()) != null) {
                    body += line;
                }
            }
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        JSONObject o = null;
        if (!body.isEmpty()) {
            try {
//                o = new JSONObject(body);
                o = XML.toJSONObject(body);
            } catch (JSONException ex) {
                ex.printStackTrace(System.out);
            }
        }
        return o;
    }
 
    public File writeCSV(String newFile, String[] columns, List<String[]> rows) {
        File f = null;
        FileWriter fichero = null;
        PrintWriter pw;
        try {
            fichero = new FileWriter(newFile);
            pw = new PrintWriter(fichero);
            for (int i = 0; i < columns.length; i++) {
                pw.print(columns[i] + (i + 1 < columns.length ? ";" : "\n"));
            }
            rows.forEach(r -> {
                for (int i = 0; i < r.length; i++) {
                    pw.print(r[i] + (i + 1 < r.length ? ";" : "\n"));
                }
            });
            f = new File(newFile);
        } catch (IOException e) {
            e.printStackTrace(System.out);
        } finally {
            try {
                if (null != fichero) {
                    fichero.close();
                }
            } catch (IOException e2) {
                e2.printStackTrace(System.out);
            }
        }
        return f;
    }
 
    public File writeJSON(String newFile, JSONObject o) {
        File f = null;
        FileWriter fichero = null;
        PrintWriter pw;
        try {
            fichero = new FileWriter(newFile);
            pw = new PrintWriter(fichero);
            pw.println(o);
            f = new File(newFile);
        } catch (IOException e) {
            e.printStackTrace(System.out);
        } finally {
            try {
                if (null != fichero) {
                    fichero.close();
                }
            } catch (IOException e2) {
                e2.printStackTrace(System.out);
            }
        }
        return f;
    }
 
    public File writeXML(String newFile, JSONObject o) {
        String root = "";
        File f = null;
        for (String k : o.keySet()) {
            root = k;
        }
        FileWriter fichero = null;
        PrintWriter pw;
        try {
            fichero = new FileWriter(newFile);
            pw = new PrintWriter(fichero);
            pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?><" + root + ">");
            pw.println(XML.toString(o));
            pw.println("</" + root + ">");
            f = new File(newFile);
        } catch (IOException e) {
            e.printStackTrace(System.out);
        } finally {
            try {
                if (null != fichero) {
                    fichero.close();
                }
            } catch (IOException e2) {
                e2.printStackTrace(System.out);
            }
        }
        return f;
    }
}

Saludos!!
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
2
Comentar

Gracias

Publicado por Israel (1 intervención) el 14/05/2019 04:27:47
Muchas Gracias, una duda mas, sabrias como almacenar lo datos del archivo en un Jtable y que el Jtable adopted las dimensiones segun los datos del.archivo?
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Billy Joel
Val: 2.665
Oro
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

Gracias

Publicado por Billy Joel (875 intervenciones) el 14/05/2019 16:24:10
Supongamos que quieres cargar la data de un archivo CSV en JTable...
Tendrías que utilizar el método que te deje arriba readCSV.
Para que un controlar la datos datos que aparecen en un JTable, tienes que hacer uso de un TableModel o un DefaultTableModel.
Entonces haciendo uso del método readCSV creamos el método loadCSV2Table para cargar la data de un archivo CSV a un DefaultTableModel.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
 * Devuelve un objeto DefaultTableModel con la data del archivo CSV
 * @param csv
 * @return 
 */
public DefaultTableModel loadCSV2Table(File csv) {
    JSONObject data = readCSV(csv);
    if (data == null) {
        return null;
    } else {
        String[] columns = (String []) data.get("columns");
        List<String []> rows = (List<String[]>) data.get("rows");
        String [][] datos = new String[columns.length][rows.size()];
        for (int i = 0; i < datos.length; i++) {
            datos[i] = rows.get(i);
        }
        return new DefaultTableModel(datos, columns);
    }
}

Entonces en la parte que vas a rellenar el JTable sería algo como:
1
2
File csv = new File("Nombre_del_archivo.csv");
jtable.setModel(loadCSV2Table(csv));
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar