quarta-feira, 27 de agosto de 2014

2014/2-ALP: Laboratório 1 Problema 3

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    // Problema:
    // Entrada: um número inteiro digitado pelo usuário
    // Saída: informar se o número é par ou impar
    
    // descricao textual
    // 1) Ler o numero inteiro do usuario
    // 2) Dividir o numero por 2
    // 3) Calcular o resto da divisao por 2
    // 4) Se o resto for zero
    // 4.1) o numero é par
    // 5) Senão
    // 5.1) o numero é impar
    
                            // ALGORITMO
    int r, q, n;            // VAR  N, Q, R: inteiro
    // INICIO
    cout << "Digite um numero inteiro:"<< endl;//   Escrever "Digite um numero:"
    cin >> n;               //   Ler N
    q = n / 2;              //   Q <- N / 2
    r = n - (q * 2);        //   R <- N - (Q * 2)
    if (r == 0){//   Se (R == 0) Então
      cout << "Numero "<<n<<" eh par!"<<endl;//     Escrever "Numero eh par!"
    }else{//   Senão
      cout << "Numero "<<n<<" eh impar!"<<endl;//     Escrever "Numero eh impar!"
    }//   Fim Se
    // FIM                
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

segunda-feira, 25 de agosto de 2014

2014/2: OdA: RandomAccessFile + java nio: Exemplo 3

RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw");
    FileChannel inChannel = aFile.getChannel();

    ByteBuffer buf = ByteBuffer.allocate(48);

    int bytesRead = inChannel.read(buf);
    while (bytesRead != -1) {

      System.out.println("Read " + bytesRead);
      buf.flip();

      while(buf.hasRemaining()){
          System.out.print((char) buf.get());
      }

      buf.clear();
      bytesRead = inChannel.read(buf);
    }
    aFile.close();

2014/2: OdA: RandomAccessFile: Exemplo 2

package br.pit.oda.arquivos.java;

import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileEx {

    static final String FILEPATH = "C:/Users/nikos7/Desktop/input.txt";

    public static void main(String[] args) {
        try {
            System.out.println(new String(readFromFile(FILEPATH, 150, 23)));
            writeToFile(FILEPATH, "JavaCodeGeeks Rocks!", 22);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static byte[] readFromFile(String filePath, int position, int size) throws IOException {

        RandomAccessFile file = new RandomAccessFile(filePath, "r");
        file.seek(position);
        byte[] bytes = new byte[size];
        file.read(bytes);
        file.close();
        return bytes;

    }

    private static void writeToFile(String filePath, String data, int position) throws IOException {

        RandomAccessFile file = new RandomAccessFile(filePath, "rw");
        file.seek(position);
        file.write(data.getBytes());
        file.close();

    }

}

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);
        }
    }
}

2014/2: OdA: RandomAccessFile: Exemplo 1

package br.pit.oda.arquivos.java;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFile03 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            // create a new RandomAccessFile with filename test
            RandomAccessFile raf = new RandomAccessFile("test.txt", "rw");

            // write something in the file
            raf.writeUTF("Hello World");

            // set the file pointer at 0 position
            raf.seek(0);

            // print the line
            System.out.println("" + raf.readLine());

            // set the file pointer at 0 position
            raf.seek(0);

            // write something in the file
            raf.writeUTF("This is an example \n Hello World");

            raf.seek(0);
            // print the line
            System.out.println("" + raf.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}