domingo, 11 de dezembro de 2005

Dica Java: lendo e escrevendo strings em arquivos, linha a linha


1. Escrevendo

try {

    // Strings a serem inseridas no arquivo.
    String[] meusLinks = new String[] {
        "http://java.sun.com",
        "http://www.linux.org",
        "http://msdn.microsoft.com/netframework"};

    // Instanciando um objeto que irá escrever no arquivo "C:\MeusLinks.txt".
    // O segundo argumento informado no construtor, quando "true", siginifica
    // que os bytes serão escritos no fim do arquivo.
    FileOutputStream meuArquivo = 
new FileOutputStream("C:\\MeusLinks.txt", 
true);



    for (int i=0 ; i<meusLinks.length ; i++) {

        // Convertendo a String para "Array" de "char"
        char[] caracteres = meusLinks[i].toCharArray();
        for (int j=0 ; j<caracteres.length ; j++) {
        meuArquivo.write( (byte)(caracteres[j]) );
        }

        // Escrevendo o byte que pula a linha
        char pulaLinha = 13;
        meuArquivo.write( (byte)(pulaLinha) );
        pulaLinha = 10;
        meuArquivo.write( (byte)(pulaLinha) );
    }

    meuArquivo.close(); // Fechando o arquivo

} catch (FileNotFoundException e) {


} catch (IOException e) {


}


2. Lendo

String linhaAtual = new String();
try {
    // Objeto leitor do arquivo "C:\MeusLinks.txt"
    FileReader fileReader = new FileReader("C:\\MeusLinks.txt");
    // Objeto que manipula o incremento/leitura das linhas do arquivo
    LineNumberReader lineNumber = new LineNumberReader(fileReader);

    // Lendo as linhas do arquivo
    while ((linhaAtual = lineNumber.readLine() ) != null ){
        System.out.println(linhaAtual);
    }
    lineNumber.close();
    fileReader.close();

} catch (FileNotFoundException e) {

} catch (IOException e) {

}

Você sabe o que é Lottie no que diz respeito ao mundo das aplicações para Windows?

Lottie-Windows is a library for rendering Adobe AfterEffects animations natively in your applications. This project adds Windows to the Lot...