java: read file txt file, put each line in arrary list and write file ; good example, to handle any file

 import java.io.*;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;


public class FileFilterAndAppend {

    public static void main(String[] args) {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    String timestamp = sdf.format(new Date());

        String filePath = "C:\\Users\\04758W744\\Desktop\\123.txt"; // Replace with your file path

        String outputPath = "C:\\Users\\04758W744\\Desktop\\456.txt"; // Replace with your desired output path


        try {

            List<String> lines = readFile(filePath);


            // Filter lines starting with "a" and append a timestamp

            List<String> filteredLines = new ArrayList<>();

            

           


            for (String line : lines) {

                if (line.startsWith("a")) {

                    filteredLines.add(line);

                }

            }


            // Display filtered lines and append them to the output file

            for (String filteredLine : filteredLines) {

                System.out.println(filteredLine);

            }


            appendLinesToFile(outputPath, filteredLines);

        } catch (IOException e) {

            e.printStackTrace();

        }

    }


    static List<String> readFile(String filePath) throws IOException {

        List<String> lines = new ArrayList<>();


        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {

            String line;

            while ((line = reader.readLine()) != null) {

                lines.add(line);

            }

        }


        return lines;

    }


    static void appendLinesToFile(String outputPath, List<String> lines) throws IOException {

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputPath, true))) {

            for (String line : lines) {

                writer.write(line);

                writer.newLine();

            }

        }

    }

}


Popular posts from this blog

SAP CPI : camle expression in sap cpi , cm, router, filter and groovy script. format

pss book: గురు ప్రార్థనామంజరి . completed 21st july 2024

pss book : శ్రీకృష్ణుడు దేవుడా, భగవంతుడా completed , second review needed. 26th April 2024