2015-03-03 53 views
0
public class FIlesInAFolder { 

     private static BufferedReader br; 

     public static void main(String[] args) throws IOException { 
      File folder = new File("C:/filesexamplefolder"); 
      FileReader fr = null; 

      if (folder.isDirectory()) { 
       for (File fileEntry : folder.listFiles()) { 
        if (fileEntry.isFile()) { 
         try { 
          fr = new FileReader(folder.getAbsolutePath() + "\\" + fileEntry.getName()); 
          br = new BufferedReader(fr); 
System.out.println(""+br.readLine()); 
         } 
         catch (FileNotFoundException e) { 
          e.printStackTrace(); 
         } 
         finally { 
          br.close(); 
          fr.close(); 
         } 
        } 
       } 
      } 
     } 
    } 

如何從目錄的第一個文件打印第一個單詞,從第二個文件打印第二個單詞並從同一個目錄的第三個文件打印第三個單詞。如何從目錄的文件中讀取數據

i am able to open directory and print the line from each file of the directory, 
but tell me how to print the first word from first file and second word from second file and so on . . 
+0

這並不容易從ditectory讀取數據... – alfasin 2015-03-03 09:29:58

+0

爲每個文件 – gstackoverflow 2015-03-03 09:30:38

+0

請修改以下問題http://stackoverflow.com/questions/14673063/merging-file-in-java創建不同的流 – gstackoverflow 2015-03-03 09:35:41

回答

0

像下面這樣的東西會從第一個文件中讀出第一個字,從第二個文件中讀取第二個字,從第n個文件中讀取第n個字。您可能需要做一些額外的工作來提高代碼的穩定性。

import java.io.File; 
import java.io.IOException; 
import java.io.FileReader; 
import java.io.BufferedReader; 
import java.io.FileNotFoundException; 

public class SOAnswer { 

    private static void printFirst(File file, int offset) throws FileNotFoundException, IOException { 

     FileReader fr = new FileReader(file); 
     BufferedReader br = new BufferedReader(fr); 

     String line = null; 
     while ((line = br.readLine()) != null) { 
      String[] split = line.split(" "); 
      if(split.length >= offset) { 
       String targetWord = split[offset]; 
      } 
      // we do not care if files are read that do not match your requirements, or 
      // for reading complete files as you only care for the first word 
      break; 
     } 

     br.close(); 
     fr.close(); 
    } 

    public static void main(String[] args) throws Exception { 
     File folder = new File(args[0]); 
     if(folder.isDirectory()) { 
      int offset = 0; 
      for(File fileEntry : folder.listFiles()) { 
       if(fileEntry.isFile()) { 
        printFirst(fileEntry, offset++); // handle exceptions if you wish 
       } 
      } 
     } 
    } 
}