segunda-feira, 25 de agosto de 2014

2014/2: OdA: Java nio Exemplo 1

package br.pit.oda.arquivos.java;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class NioExample {

    /**
     * @param args
     */
    public static void main(String[] args) {

        String s = "Bom dia a todos!\n";
        byte data[] = s.getBytes(); // converte o String para bytes
        ByteBuffer out = ByteBuffer.wrap(data); // cria um buffer de bytes

        ByteBuffer copy = ByteBuffer.allocate(12); // cria um novo buffer de bytes

        Path path = Paths.get("/temp/teste.txt"); // criar um caminho para um arquivo

        FileChannel fc = null;
        try {
            // abre um canal de arquivo
            fc = (FileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE));
            int nread;
            do {
                nread = fc.read(copy); // lendo 12 bytes do arquivo
            } while ((nread != -1) && copy.hasRemaining());

            // escrevendo a frase no início do arquivo
            fc.position(0);
            while (out.hasRemaining()) {
                fc.write(out);
            }
            out.rewind(); // rebobinando o buffer

            // movendo para o fim do arquivo
            // copiando os 12 primeiros bytes no fim do arquivo
            long length = fc.size();
            fc.position(length - 1);
            copy.flip(); // inverte o buffer de bytes
            while (copy.hasRemaining()) {
                fc.write(copy);
            }
            while (out.hasRemaining()) {
                fc.write(out);
            }
            fc.close();
        } catch (IOException x) {
            System.out.println("I/O Exception: " + x);
        }
    }
}

Nenhum comentário:

Postar um comentário