Txt file manipulation in JAVA

2

Hello, I'm a beginner in java and I need to create a program that creates a txt file with a pre defined content, read it and divide the contents of this file into two different txt files. start with // (java comments) and pass the rest (it will be a java code) to the second file and finally compile that code.

Most of the program I can do, but my doubt is in the part where I need to pass the content to a different file.

public static void main(String[] args) throws IOException {
    //conteudo
    String conteudo = "arquivo inicial\nlinha2"; //conteudo inicial
    String conteudo1 = null; //o que vai ser separado para o arquivo1(comentarios)
    String conteudo2 = null; //o que vai ser separado para o arquivo2(codigo a ser compilado)

    //cria os 3 arquivos (inicial , txt dos comentarios e txt do codigo
    File arquivo = new File("arquivo.txt");
    File arquivo1 = new File ("arquivo1.txt");
    File arquivo2 = new File("arquivo2.txt");

    //prepara pra escrever no arquivo inicial 
    FileWriter fw = new FileWriter(arquivo.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);

    //escreve e fecha o arquivo
    bw.write(conteudo);
    bw.close();

    //le o arquivo linha por linha
    FileReader ler = new FileReader("arquivo.txt");
    BufferedReader reader = new BufferedReader(ler);
    String linha;
    while( (linha = reader.readLine()) != null) {
        System.out.println(linha);  //printa linha por linha do arquivo inicial
        if (linha.contains("//")) {    //se o arquivo conter // , ele separa para outro arquivo
            }
        else {

        }
    }

    }

My doubts are: if what if the line contains two bars (in the case the comment in java) should be in or out of the while while the file until there is nothing else to read, and which command I can use within the if that is able to separate just the lines with comments and create a new string with it?

Many thanks to everyone

    
asked by anonymous 20.04.2018 / 21:59

1 answer

2

I completed your code with a very simple implementation. I recommend using the new File Classes of Java 7 for file manipulation, as they have some methods that abstract the writing and reading of files from your code.

Implementation:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.ArrayList;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        //Conteudo inicial.
        String conteudo = "Linha Codigo\n//Comentario"; //conteudo inicial

        //Obtem um path para cada um dos 3 arquivos (inicial ,comentarios e txt do codigo
        Path arquivoInicial = Paths.get("arquivoInicial.txt");
        Path arquivoComentarios = Paths.get("arquivoComentarios.txt");
        Path arquivoCodigo = Paths.get("arquivoCodigo.txt");

        //Escreve o conteudo inicial
        Files.write(arquivoInicial, conteudo.getBytes());

        //Chama a funcao de fitro, pasando o arquivo Origem e os arquivos de destino.
        filtrarComentarios(arquivoInicial, arquivoComentarios, arquivoCodigo);
    }

    /**
     * Filtra o codigo de um arquivo, separando em código e comentarios.
     */
    public static void filtrarComentarios(Path arquivoInicial, Path arquivoComentarios, Path arquivoCodigo) throws IOException {
        //Cria duas listas para armazenar o codigo e comentarios.
        List<String> comentarios = new ArrayList<>();
        List<String> codigo = new ArrayList<>();

        //Itera todas as linhas do arquivoInicial, o método readAllLines de Files retorna uma Lista
        //de String que denota as linhas do arquivo.
        for (String linha : Files.readAllLines(arquivoInicial, StandardCharsets.UTF_8)) {
            //Utiliza o método trim() para que qualquer comentario seja detectado, o método trim() remove todo whitespace(espaco, tabs) do inicio e fim da String.
            if (linha.trim().startsWith("//")) {
                comentarios.add(linha);
            } else {
                codigo.add(linha);
            }
        }

        //Escreve o resultado em cada arquivo.
        Files.write(arquivoComentarios, comentarios);
        Files.write(arquivoCodigo, codigo);
    }
}

The idea of the code is to iterate over all the lines of the files and to filter lines whose initial characters are // , after iteration the result is written in both files.

It is important to note that the methods used in class Files throw the IOException exception in case an error occurs while writing / reading a file, thus interrupting execution, it is recommended that this error be handled with a try / catch block but it was not meant to simplify implementation.

    
21.04.2018 / 00:49