1   package eu.fbk.knowledgestore.populator.naf;
2   
3   import java.io.BufferedWriter;
4   import java.io.File;
5   import java.io.FileInputStream;
6   import java.io.FileOutputStream;
7   import java.io.IOException;
8   import java.io.InputStream;
9   import java.io.OutputStream;
10  import java.io.OutputStreamWriter;
11  import java.io.Writer;
12  
13  import javax.xml.bind.JAXBException;
14  
15  public class groupTxtF {
16  	static OutputStream out;
17  	/**
18  	 * @param args
19  	 * @throws IOException 
20  	 * @throws JAXBException 
21  	 * @throws ClassNotFoundException 
22  	 * @throws SecurityException 
23  	 * @throws NoSuchMethodException 
24  	 * @throws IllegalAccessException 
25  	 * @throws InstantiationException 
26  	 */
27  	public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, ClassNotFoundException, JAXBException, IOException {
28  		
29  		analyzePathAndRunSystem(args[0]);
30  	}
31  	private static void analyzePathAndRunSystem(String path) throws JAXBException, IOException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, ClassNotFoundException {
32  		File filePath = new File(path);
33  		if(filePath.exists()&&filePath.isDirectory()){
34  			//create report file in the same directory of running the system
35  			  out = new FileOutputStream(new File(filePath.getPath(), "groupedReport.txt"));
36  
37  			 File[] listOfFiles = filePath.listFiles(); 
38  			  for (int i = 0; i < listOfFiles.length; i++) 
39  			  {
40  				 // System.out.println(listOfFiles[i].getName());
41  			   if (listOfFiles[i].isFile()&&listOfFiles[i].getName().endsWith(".txt")) 
42  			   {
43  				 System.err.println(i+"="+listOfFiles[i].getName());
44  			   //out.append("\n"+i+"="+listOfFiles[i].getName()+"\n");
45  				 copyFile(listOfFiles[i]);
46  			   }
47  			   out.flush();
48  			   System.gc();
49  			   Runtime.getRuntime().gc();
50  			  }
51  			  out.flush();
52  			  out.close();
53  		}else if(filePath.exists()&&filePath.isFile()) {
54  			System.err.println("It isn't efficient to group one file in one file");
55  		}
56  		out.flush();
57  		out.close();
58  	}
59  	 static void copyFile(File source) {
60  	        if (source == null || !source.exists())
61  	            return;
62  	        try{
63  
64  	            InputStream inStream = new FileInputStream(source);
65  
66  	            byte[] buffer = new byte[1024];
67  
68  	            int length;
69  	            while ((length = inStream.read(buffer)) > 0) {
70  	                out.write(buffer, 0, length);
71  	            }
72  
73  	            inStream.close();
74  	            out.flush();
75  	            //System.out.println("File copied into " + target);
76  	        }catch(IOException e) {
77  	            e.printStackTrace();
78  	        }
79  	    }
80  
81  }