Java:从文件夹中读取所有.txt文件,然后移动到新文件夹

时间:2023-02-05 14:01:32

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)...

帮助,我需要读取文件夹中的每个.txt文件,然后将其全部复制/移动到新文件夹。但是,我需要复制每个.txt文件中的文本并创建一个变量(1 .txt文件到1个变量)。我只有这个代码只能读取1个.txt文件,然后将.txt文件中的文本复制到另一个文件夹中的另一个.txt文件中,然后将.txt中的文本创建为变量(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:

亲爱的cybi,请看下面的代码:

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));
    }
}

2 个解决方案

#1


1  

You have 4 little problems here:

这里有4个小问题:

  1. Get the files from a directory.
  2. 从目录中获取文件。

  3. Filter them by their filename suffix.
  4. 按文件名后缀过滤它们。

  5. Get their content and save them somewhere.
  6. 获取他们的内容并将其保存在某个地方。

  7. Move the files to another directory.
  8. 将文件移动到另一个目录。

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

如果你像这样组织你的代码,那就很容易了(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.

使用java.nio包就可以轻松实现。

#2


0  

You can use Filefilter also

您也可以使用Filefilter

 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);
        }

#1


1  

You have 4 little problems here:

这里有4个小问题:

  1. Get the files from a directory.
  2. 从目录中获取文件。

  3. Filter them by their filename suffix.
  4. 按文件名后缀过滤它们。

  5. Get their content and save them somewhere.
  6. 获取他们的内容并将其保存在某个地方。

  7. Move the files to another directory.
  8. 将文件移动到另一个目录。

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

如果你像这样组织你的代码,那就很容易了(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.

使用java.nio包就可以轻松实现。

#2


0  

You can use Filefilter also

您也可以使用Filefilter

 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);
        }