dimecres, 2 de març del 2016

Lectura y escritura de ficheros en Java

Podemos hacer la lectura y escritura de ficheros con FileInputStream, que va carácter a carácter.
public class Stream {
public static void main(String[] args) throws IOException {

    FileInputStream in = null;
    FileOutputStream out = null;

    try {
        in = new FileInputStream("entrada.txt");
        out = new FileOutputStream("sortida.txt");
        int c;

        while ((c = in.read()) != -1) {
            System.out.println(c);
            out.write(c);
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
    }
}
}
o podemos utilizar las lecturas con buffered.

public class ReaderWriter {
public static void main(String[] args) throws IOException {

    BufferedReader inputStream = null;
    PrintWriter outputStream = null;

    try {
        inputStream = new BufferedReader(new FileReader("entrada.txt"));
        outputStream = new PrintWriter(new FileWriter("sortida.txt"));

        String l;
        while ((l = inputStream.readLine()) != null) {
            System.out.println(l);
            outputStream.println(l);
        }
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        if (outputStream != null) {
            outputStream.close();
        }
    }
}
}

1 comentari :