(Java) Read TXT (input) and generate TXT (output) with organized information

Asked

Viewed 59 times

0

I need to make the following logic: 1- Read a txt with several lines, each line has an activity EX: Walk 10min, Study 30min... (each activity in a row). 2- Half day lunch time. 3- Organize the activity by time that each takes to be executed, before and after lunch. 4-Save output txt with organized information.

My code so far

    public static void main(String[] args) throws IOException {
    // TODO code application logic here
    try {
        Scanner ler = new Scanner(System.in);

        String nomePc = System.getProperty("user.name");
        String path = "C:\\Users\\" + nomePc + "\\Desktop\\input.txt";
        String outputDir = "C:\\Users\\" + nomePc + "\\Desktop\\output.txt";

        FileReader arq = new FileReader(path);
        BufferedReader lerArq = new BufferedReader(arq);
        String linha = lerArq.readLine();

        //Output   
        File file2 = new File(outputDir);
        FileWriter arq_output = new FileWriter(file2, true);
        PrintWriter gravarArq = new PrintWriter(arq_output);

        if (!file2.exists()) {
            // Como o arquivo não existe, cria um novo arquivo
            file2.createNewFile();
        }

        while (linha != null) {

           linha = lerArq.readLine();

            System.out.println(linha);
            String trinta_min = "30min";
            linha.toLowerCase().contains(trinta_min.toLowerCase());

        }
        lerArq.close();
        gravarArq.close();
        arq.close();

    } catch (IOException e) {

        System.out.printf("Erro ao localizar o arquivo: %s.", e.getMessage());

    };
}

Doubt: If I use the variable linhasto track the value of each activity with the idea to return true or false makes a mistake (at xxxxx.xxxxx.main(null xxxx.java:63)) and (Exception in thread "main" java.lang.NullPointerException).

String trinta_min = "30min";
linha.toLowerCase().contains(trinta_min.toLowerCase()));

If someone has suggestions in other ways, it is also acceptable.

1 answer

1


You can test if the line is null before calling linha.toLowerCase().

    while (linha != null) {

       linha = lerArq.readLine();

        System.out.println(linha);
        String trinta_min = "30min";

        boolean sao30min = false;
        if (linha != null) {
            sao30min = linha.toLowerCase().contains(trinta_min.toLowerCase());
        }
    }

Note: You may be interested in the methods:

Browser other questions tagged

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