2017-02-24 73 views
-1

幫助,我需要讀取文件夾中的每個.txt文件,然後將其全部複製/移動到新文件夾中。 但是,我需要複製每個.txt文件內的文本,併爲它們創建一個變量(1.txt文件爲1個變量)。我只有這樣的代碼,只能讀取1.txt文件,然後將.txt文件中的文本複製到另一個文件夾中的另一個.txt文件,並將它創建爲變量(aLine)中的.txt文本...Java:讀取文件夾中的所有.txt文件,然後移至新文件夾

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

親愛錫比, 請看看我的代碼波紋管:

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

從Apache公共庫使用FileUtils http://stackoverflow.com/questions/1146153/copying-files-from-one-directory-to-another-in-java – user121290

回答

1

你這裏有4個個小問題:

  1. 從目錄中獲取文件。
  2. 通過文件名後綴對它們進行過濾。
  3. 獲取他們的內容並將它們保存在某個地方。
  4. 移動文件到另一個目錄。

如果你喜歡組織你的代碼,它會很容易(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)); 
    } 
} 

隨着包java.nio中它只是這麼簡單。

+0

親愛的cybi,我最後一個問題哈哈...你有沒有參考使用Files.write?即時通訊試圖得到它,但我認爲即時通訊的死衚衕......我將使用作家將內容寫入ActiveMQ的製作人... – NWD

+0

你可以在https://docs.oracle.com/找到例子。 JavaSE的/教程/本質/ IO/file.html。但是你不能用它來寫隊列!它僅適用於文件。要寫入ActiveMQ隊列,請查看http://activemq.apache.org/hello-world.html。 – cybi

+0

Ohh okok ... btw我可以使用BufferedReader讀取像Files.readAllBytes這樣的文件夾內的所有.txt內容嗎? – NWD

0

可以使用的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); 
     } 
相關問題