-1

Help, i need to read every .txt file in a folder then copy/move it all to the new folder. But, i need to copy the text inside every .txt file and create them a variable (1 .txt file to 1 variable). I only got this code that only can read 1 .txt file then copying the text inside the .txt file to another .txt file in another folder and it creating the text inside .txt into variable (aLine)...

public static void main(String[] args) throws IOException {

    String source = File.separator + "C:\\Users\\NN\\Documents\\Test1\\Source.txt";
    String dest = File.separator + "C:\\Users\\NN\\Documents\\Test2\\Empty.txt";

    File dir = new File(".");

    File fin = new File(source);
    FileInputStream fis = new FileInputStream(fin);
    BufferedReader in = new BufferedReader(new InputStreamReader(fis));

    FileWriter fstream = new FileWriter(dest, true);
    BufferedWriter out = new BufferedWriter(fstream);

    String aLine = null;
    while ((aLine = in.readLine()) != null) {
        System.out.println(aLine);
        out.write(aLine);
        out.newLine();
    }

    in.close();

    out.close();
}

dear cybi, pls look at my code bellow:

import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class NewMass {
    private ConnectionFactory factory = null;
    private Connection connection = null;
    private Session session = null;
    private Destination destination = null;
    private MessageProducer producer = null;

    File dir = new File(".");

    String aLine = null;

    static Map<Path, List<String>> contentOfFiles;

    public static void main(String[] args) throws IOException {
        String source = "C:\\Users\\NN\\Documents\\Test1";
        String target = "C:\\Users\\NN\\Documents\\Test2";

        List<Path> filePaths = filePathsList(source); // Step 1: get all files from a directory
        List<Path> filteredFilePaths = filter(filePaths); // Step 2: filter by ".txt"
//        Map<Path, List<String>> contentOfFiles = getContentOfFiles(filteredFilePaths); // Step 3: get content of files
        contentOfFiles = getContentOfFiles(filteredFilePaths); // Step 3: get content of files
        NewMass prdcr = new NewMass();
        move(filteredFilePaths, target); // Step 4: move files to destination
        printToConsole(contentOfFiles);
    }

    public NewMass() throws IOException {
        try {
            factory = new ActiveMQConnectionFactory(
            ActiveMQConnection.DEFAULT_BROKER_URL);
            connection = factory.createConnection();
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            destination = session.createQueue("TestQueue");
            producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            //String text = in.readinLine();
            String text = contentOfFiles.get(filePath);
            TextMessage message = session.createTextMessage(text);
            producer.send(message);
            System.out.println("Sent: " + message.getText());

            while ((aLine = contentOfFiles.get(filePath)) != null) {
                message = session.createTextMessage(aLine);
                System.out.println("Sent message: "+  message.getText());
                producer.send(message);

                }
        }
        catch (JMSException e) {
            e.printStackTrace();
        }
    }

    public static List<Path> filePathsList(String directory) throws IOException {
        List<Path> filePaths = new ArrayList<>();
        DirectoryStream<Path> directoryStream = Files.newDirectoryStream(FileSystems.getDefault().getPath(directory));
        for (Path path : directoryStream) {
            filePaths.add(path);
        }
        return filePaths;
    }

    private static List<Path> filter(List<Path> filePaths) {
        List<Path> filteredFilePaths = new ArrayList<>();
        for (Path filePath : filePaths) {
            if (filePath.getFileName().toString().endsWith(".txt")) {
                filteredFilePaths.add(filePath);
            }
        }
        return filteredFilePaths;
    }

    private static Map<Path, List<String>> getContentOfFiles(List<Path> filePaths) throws IOException {
        Map<Path, List<String>> contentOfFiles = new HashMap<>();
        for (Path filePath : filePaths) {
            contentOfFiles.put(filePath, new ArrayList<>());
            Files.readAllLines(filePath).forEach(contentOfFiles.get(filePath)::add);
        }
        return contentOfFiles;
    }

    private static void move(List<Path> filePaths, String target) throws IOException {
        Path targetDir = FileSystems.getDefault().getPath(target);
        if (!Files.isDirectory(targetDir)) {
            targetDir = Files.createDirectories(Paths.get(target));
        }
        for (Path filePath : filePaths) {
            System.out.println("Moving " + filePath.getFileName() + " to " + targetDir.toAbsolutePath());
            Files.move(filePath, Paths.get(target, filePath.getFileName().toString()), StandardCopyOption.ATOMIC_MOVE);
        }   
    }

    private static void printToConsole(Map<Path, List<String>> contentOfFiles) {
        System.out.println("Content of files:");
        contentOfFiles.forEach((k,v) -> v.forEach(System.out::println));
    }
}
NWD
  • 77
  • 2
  • 10
  • Use FileUtils from apache commons library http://stackoverflow.com/questions/1146153/copying-files-from-one-directory-to-another-in-java – Karthik Bharadwaj Feb 24 '17 at 07:54

2 Answers2

1

You have 4 little problems here:

  1. Get the files from a directory.
  2. Filter them by their filename suffix.
  3. Get their content and save them somewhere.
  4. Move the files to another directory.

If you organize your code like that, it gets quite easy (Java 8):

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {

    public static void main(String[] args) throws IOException {
        String source = "source";
        String target = "target";

        List<Path> filePaths = filePathsList(source); // Step 1: get all files from a directory
        List<Path> filteredFilePaths = filter(filePaths); // Step 2: filter by ".txt"
        Map<Path, List<String>> contentOfFiles = getContentOfFiles(filteredFilePaths); // Step 3: get content of files
        move(filteredFilePaths, target); // Step 4: move files to destination
        printToConsole(contentOfFiles);
    }

    public static List<Path> filePathsList(String directory) throws IOException {
        List<Path> filePaths = new ArrayList<>();
        DirectoryStream<Path> directoryStream = Files.newDirectoryStream(FileSystems.getDefault().getPath(directory));
        for (Path path : directoryStream) {
            filePaths.add(path);
        }
        return filePaths;
    }

    private static List<Path> filter(List<Path> filePaths) {
        List<Path> filteredFilePaths = new ArrayList<>();
        for (Path filePath : filePaths) {
            if (filePath.getFileName().toString().endsWith(".txt")) {
                filteredFilePaths.add(filePath);
            }
        }
        return filteredFilePaths;
    }

    private static Map<Path, List<String>> getContentOfFiles(List<Path> filePaths) throws IOException {
        Map<Path, List<String>> contentOfFiles = new HashMap<>();
        for (Path filePath : filePaths) {
            contentOfFiles.put(filePath, new ArrayList<>());
            Files.readAllLines(filePath).forEach(contentOfFiles.get(filePath)::add);
        }
        return contentOfFiles;
    }

    private static void move(List<Path> filePaths, String target) throws IOException {
        Path targetDir = FileSystems.getDefault().getPath(target);
        if (!Files.isDirectory(targetDir)) {
            targetDir = Files.createDirectories(Paths.get(target));
        }
        for (Path filePath : filePaths) {
            System.out.println("Moving " + filePath.getFileName() + " to " + targetDir.toAbsolutePath());
            Files.move(filePath, Paths.get(target, filePath.getFileName().toString()), StandardCopyOption.ATOMIC_MOVE);
        }   
    }

    private static void printToConsole(Map<Path, List<String>> contentOfFiles) {
        System.out.println("Content of files:");
        contentOfFiles.forEach((k,v) -> v.forEach(System.out::println));
    }
}

With package java.nio it's just that easy.

cybi
  • 99
  • 5
  • Dear cybi, ive one last question lol... did you have a reference to using the Files.write? im trying to get it but i think im on a dead end lol... i'll use the writer to write the content into the ActiveMQ's producer... – NWD Mar 03 '17 at 07:26
  • You can find examples at https://docs.oracle.com/javase/tutorial/essential/io/file.html. But you cannot use it to write to a queue! It is for Files only. For writing to an ActiveMQ queue have a look at http://activemq.apache.org/hello-world.html. – cybi Mar 03 '17 at 08:04
  • Ohh okok... btw can i use BufferedReader to read all .txt's content inside a folder like the Files.readAllBytes? – NWD Mar 03 '17 at 08:53
  • You can use a BufferedReader, of course. It is just easier and shorter with Files.readAllBytes. You might want to use it because of compatibility issues, when the code needs to run with older Java versions. – cybi Mar 03 '17 at 23:29
  • Yea... i want to send 2 message if there was 2 line in 1 .txt file... and i cant use the Files.readAllBytes, bcs it will be sent as 1... have u a link's reference to use the BufferedReader on a folder just like the File.readAllBytes that u told me? – NWD Mar 06 '17 at 03:00
  • Or maybe can u help me to change ur 3rd step's code become using bufferedreader? – NWD Mar 06 '17 at 03:53
  • You should use Files.readAllLines in this case. Have a look at https://kodejava.org/how-do-i-read-all-lines-from-a-file/ – cybi Mar 06 '17 at 06:09
  • ohh ok, that Files.readAllLines still can read all the .txt file in a folder right? so i just need to change ur code a little become Files.readAllLines – NWD Mar 06 '17 at 06:17
  • Yes, I will change it later. You could try it before. – cybi Mar 06 '17 at 06:26
  • im on a dead end :| – NWD Mar 06 '17 at 08:23
  • What's the problem? I have just updated the answer now. – cybi Mar 06 '17 at 08:35
  • I've edited my question, pls look at the second code... The public NewMass class is the code for checking connection and sent the message to ActiveMQ... – NWD Mar 06 '17 at 09:09
  • You can use the code of printToConsole and replace the System.out... by your code in NewMass. For example you could add a parameter to the method and replace in.readLine() by its name. – cybi Mar 06 '17 at 10:46
  • Parameter outside the class? I just need to fix when the code getting the contentOfFile and the looping for every line? Which is i need to create a parameter outside the main, right? – NWD Mar 07 '17 at 03:18
  • The problem with your code is, that you do not forward the Map "contentOfFiles" to the constructor. You created a constructor NewMass, but you don't need it. You need a method like "printToConsole", which iterates over the entries of the Map "contentOfFiles". Have a look at https://github.com/cybi/stackoverflow/blob/master/42432893/src/test/Main.java#L81. – cybi Mar 07 '17 at 09:12
  • Btw if i want to sort the file by its last modified time, i only need to change the filtering step right? – NWD Mar 08 '17 at 03:29
  • That won't help. You have a HashMap there, which has to be changed to a i.e. TreeMap. BTW all your questions are usually new questions on SO. This is already support for your different problems. I understand you are new to Java, but this has already gone too far. If you need further assistance, please contact me on github. – cybi Mar 08 '17 at 07:06
  • ohh ok... i guess so, thats really far from my question... Ty btw... ill contact u from github if ur ok with that... – NWD Mar 08 '17 at 07:27
0

You can use Filefilter also

 File source = new File("E:\\log\\vpa");
        File dest = new File("E:\\log\\vpa\\copied");
        try {
            FileUtils.copyDirectory(source, dest, new FileFilter() {

                @Override
                public boolean accept(File pathname) {

                    if (pathname.getName().toLowerCase().endsWith(".txt"))
                        return true;
                    return false;
                }
            });
        } catch (IOException e) {
          Exceptions.propagate(e);
        }