Java - Insertar datos y exportarlos a un fichero

 
Vista:
sin imagen de perfil

Insertar datos y exportarlos a un fichero

Publicado por Victor (1 intervención) el 22/08/2013 10:48:53
Buenos días,

Os agradecería enormemente un cable.
El siguiente código crea un fichero txt a partir de datos introducidos:
- pide al usuario que determine el nombre del fichero
- comprueba si existe
- si no existe, lo crea y si existe, pregunta si desea sobreescribir.
- lo cierra

Sin embargo, el programa se termina en el momento que se escribe el nombre del fichero y no sé por qué.

Por otro lado, tengo dudas:
- qué estamos diciendo con lo que se encuentra entre paréntesis?



nombrefichero=new String(buffer,0,nbytes-2);


ESTE ES EL CÓDIGO DEL PROGRAMA
GRACIAS POR ADELANTADO

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
package escribirdatos;
import java.io.*;
 
public class EscribirDatos {
 
 
    public static void main(String[] args) {
        FileWriter fs=null;
        byte[] buffer=new byte[81];
        int nbytes;
        String nombrefichero=null;
        File fichero=null;
 
        try
        {
            System.out.print("Escriba el nombre del fichero: ");
            nbytes=System.in.read(buffer);
            nombrefichero=new String(buffer,0,nbytes-2);
            fichero=new File(nombrefichero);
 
            char resp= 's';
            if (fichero.exists())
            {
                System.out.print("El fichero existe, desea sobreescribirlo? s/n ");
                resp=(char)System.in.read();
                System.in.skip(System.in.available());
            }
            if (resp=='s')
            {
                System.out.print("Escribe el texto que desea almacnar en el fichero");
                nbytes=System.in.read(buffer);
                String str=new String(buffer,0, nbytes);
                fs=new FileWriter(fichero);
                fs.write(str,0,str.length());
            }
        }
        catch (IOException e)
        {
            System.out.println("Error: "+e.toString());
        }
        finally
        {
            try
            {
                if (fs!=null) fs.close();
            }
            catch (IOException e)
            {
                System.out.println("Error :"+e.toString());
 
            }
        }
    }
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

Insertar datos y exportarlos a un fichero

Publicado por Mercedes (1 intervención) el 22/08/2013 11:46:13
Hola

He estado probando tu código y funciona, solamente me ha dado error a la hora de si no pones una ruta para el archivo, es decir, he probado "C:\prueba.txt" y funciona correctamente.
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