Manipulating txt files in JAVA

Asked

Viewed 1,446 times

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 , the contents being passed to the first file all lines starting with // (java comments) and pass the rest (will be a java code) to the second file and finally commits this code.

Most of the program I can do, but my doubt is at 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 the line contains two bars (in case the comment in java) it should stay inside or outside while reading the file until there is nothing else to read , and what command I can use inside if that is able to separate only the comment lines and create a new string with it?

Thank you all very much

1 answer

2


I completed your code with a very simple implementation. I recommend using the new Java 7 File Classes (Apis) 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 code is to iterate over all lines of files and filter lines whose initials are //, after iteration the result is written in both files.

It is important to note that the methods used in the class Files launch the Ioexception exception exception if an error occurs while writing/reading a file, thus interrupting execution, it is recommended that this error be treated with a Try/catch block but not done to simplify the implementation.

  • I understood perfectly, and I was already thinking of putting in a Try/catch block to treat the exceptions , but because it is a personal question I preferred to leave so to save time, but thank you very much for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.