Categories for files in Java
If you are a Java programmer, maybe you have been very clear about Java's file organization, for example, you know how your project group is classified, forming a whole project engineering. Usually, you may be based on business. Sometimes As a member of the project, we will classify your Java file according to the group. Below, give an example: a project ProjectX wants to give a information system that COMX's commercial company, according to business needs , A, B, C, D, using a typical three-layer structure, where the files in the project are divided into the front part and the background part. After analysis, the project finally organizes the file to such a structure: The packet where the front file is located is com.comx.foreg.a, and the corresponding background file is placed in the front file where the front file written in COM.COMX.BACKG.A is com.comx.foreg.b, corresponding to The background file is placed in the packet where the front file written in COM.COMX.BACKG.B is com.comx.foreg.c, and the corresponding background file is placed in the front desk written in COM.COMX.BACKG.C. The package is located for com.comx.foreg.d, and the corresponding background file is placed in com.comx.backg.d, this is just a simplified model, and the actual project is integrated due to business crossings. The degree and other factors should be more complicated than such structures. The last code is placed on the folder "D: / Projectx / src /" below, and the following file organization and Java packet path may not The same. Now, I describe what I want to explain. After this project has been basically completed, all teams have modified, integrated publishers, and open a FTP for the project group, the FTP file structure is just like the original structure. After the programmers in group A modified a file, followed by his location, so that someone usually brings the code to the location, and finally occurs when compiling, and complex, each group has In terms of intersection, it is difficult to check the error when compiling.
What is going to do now is that all the modified files are all transmitted into a folder, and these files are distributed to the position they should be in.
Ok, how to make? Thinking is very simple: each file has their packet path, since we already have a complete file structure, we can know the path in the file organization corresponding to each package, if there is one File Classx.java, we use his packet path to com.comx.Foreg.a.a1, A1 is a group A, but its actual location is: D: / ProjectX / SRC / Business_1 / COM /comx/foreg/a/a1/Classx.java, we have another file Calssy.java, his package is com.comx.foreg.a.a2, it is the second use case in group A, but his actual storage The path is: d: /projectx/src/business_2/com/x/forg/a/a2/classy.java, we can find his suitable location according to the SRC directory specified in advance. I do is the project group The programmer's upload file provides convenience, they will upload the file you want to upload to a folder, then copy to the correct location through this program. Below is some of the modules I implemented, you can modify it according to your own special circumstances or Expand.
0. Processing this question Need to set some class variables: private string filepath = "d: // work // Upload"; // File upload path, directly point to your ftp directory, private string configefile = "packageconfig.cxh"; / / Path configuration file, will tell the private string objPath = "d: // work // gdlt // sRC"; // Target file path, you can specify any, but you want and configuration file consistent private printstream ps = null ; / / Output message redirection, the information output orientation private arraylist lines = null during processing; // Save the configuration file String [] heads = null; // Save each configured head String GlobalLine; // Record one Configuration Information 1. Incorporate a Java file, return the Package path of the Java file, such as Classx.java above, return com.comx.foreg.a / ** * read a java file, return to his package information * @Param File file handle * @return return Package path * / private string readpac (file file) {string pac = null; try {buffredreader fr = new bufferedReader (new fileReader (file); // Reader string line = Fr.readline (); while (line! = null) {// progressive process // Processing the current line line.trim (); if (line.startswith ("package") { // Find the package information Pac = line.substring (7, line.Length () - 1) .trim (); break;} line = fr.readline ();}} catch (ooException IE {PAC = null; IE.printStackTrace ();} Return PAC;
2. According to the packet path returned above, returns the actual location of the file, such as the above Classx.java, return D: / Projectx / src / business_2 / com / comx / foreg / a / / ** * * via package The information should be taken out of the location * @Param pack Package path * @RETURN Returns the file should return NULL to indicate the identification failure, you need to read, such as SBZS * and smart update configuration file * / private string parsepac String pack, file cfgfile; swright path = null; string line = null; try {for (int i = 0; i 3. According to the actual position returned above, you can copy the file to the appropriate position. Successfully returned TRUE / ** * Copy the file to the full path to * @Param File file handle * @Param path file target Absolute path * @Return * / private boolean copy (file file, string fullpath) {ps.println ("Start Copy File ..."); ps.println ("Source File: File.getName ()); ps.println ("Target File:" FullPath); string filename = file.getname (); int pos = filename.lastIndexof (file.seParetor); if (pOS> 0) {filename = filename.substring (POS 1, filename.length ());} String lastpath = fullpath file.separator filename; file objfile = new file (lastpath); if (objfile.exists () &&! Objfile.delete ()) {// If there is is deleted ps.println ( "deletion target file failed"); return false;} // start copying try {objFile.createNewFile (); FileInputStream fis = new FileInputStream (file); FileOutputStream fos = new FileOutputStream (objFile); byte [ ] buf = new byte [1024]; INT i = 0; while ((i = fis.read (buf))! = - 1) {Fos.Write (buf, 0, i);} fis.close (); Fos.close ();} catch (ioException ie) {ie.printstacktrace (); Return true;} You may have noticed it so far, all of which is very simple, the idea of the module is also very clear. Of course, you will definitely notice, where the most important role is the configuration file, if not This, you can see that in the PARSEPAC method, you will ask your console to enter a target path corresponding to a file, which is for new files (that is, the files in the original target directory, newly added), for the old file Modify, we can get the target path in the configuration file. Let's take a look at how the configuration file is obtained. Before this, we mentioned several tool methods: 1. Take the file name extension, incompart the file name, return Extension. / ** * * @Param filename * @Return * / private string getExt (string filename) {int pos = filename.lastIndexof ("."); If (pos> 0) {Return FileName.Substring (POS 1, filename.length ());} return null;} 2. Determine if a directory has a subdirectory, incoming a directory, and determined that there is no subdirectory, there is no need to return true, there is a subdirectory to return false / ** * to determine if there is a subdirectory, did not return true * @Param Dir * @return * / private boolean Hasnosub (String Directory) {file dir = new file (directory); if (! Dir.Indirectory ()) {// The current is not a directory, affirm no subdirectories return true;} string [] Subs = dir.list (); for (int i = 0; i 2. Analyze the head of a configuration information is the tophead / ** * of the above method, the first example of a configuration file, such as business_1: * @Param Line, a configuration file * @return * / private string gethead (string line) { INT POS = line.indexof (":"); if (pOS == - 1) {ps.println ("The configuration file is wrong"); return "";} return line.substring (0, POS); The method of this method is to write the information of our class variable Lines to the configuration file, because there may be newly added files, the user enters new configuration information, or when interactive, some configuration information change . / ** * Write configuration file * @Return * / private boolean savecfg (file cfgfile) {if (lines == null || lines.size () == 0) {Return False; Try {cfgfile.delete (); cfgfile.createNewFile (); bufferedwriter bw = new bufferedwriter; int size = lines.size (); for (int i = 0; i The above method is a process of our interaction of us and profiles. We will initialize this configuration file when we next problem, basically there are several modules: 1. This is the foundation of our build file, actually The process of collecting structural information in the target path, which may call some tool methods. / ** * Generate a configuration file * @Param PAC Package path * @Param Path file path * @returN returns to save correct * / public boolean createcfg () {File dir = new file (objPath); // to the target path to collect information String [] DIRS = Dir.List (); string curdir; char SEP = file.separatorchar; string line; for (int i = 0; I 2. Currently collective information in the current subdirectory, for each path, we only save the longest, because short is a long path match. / ** * recursive collection * @Param root Previous directory * @Param Pack Currently Collected Information * / Private Void getPath (String root, string pack) {if (HASNOSUB (root)) {// If there is no subdirectory IF (Globaline == null) {globalline = Pack; Else {GlobalLine = "|" pack;} return;} file dir = new file (root); char SEP = file.seParatorChar; string [] Subs = dir.list (); for (int i = 0; i < Subs.length; i ) {string curpath = root sep subsis [i]; file tmp = new file (curpath); if (tmp.isdirectory ()) {if (pack == null) {// If it is a directory After recursing getPath (Curpath, Subs [i]);} else {getPath (Curpath, Pack ". SUBS [I]);}}}}, which is used in the class variable Globalline, which eventually calls when calling, Will return a complete configuration information. Ok, I will talk so much, I don't know if I have explained it, I hope to help you, thank you, the last method is an Excute method, which is the work of this complete classification copy file. I put complete class In the following, it is not written. (This class has the traces of my own project, but not much, change it slightly) import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import Java.io.filewriter; import java.io.ioException; import java.io.printStream; import java.util.arraylist; / ** * Title: p> * Description: p> * Copyright: Copyright (c) 2004 p> * Company: p> * @ Author caoxh * @version 1.0 * / Public class savefile = "d: // work // upload"; // File upload path private string configefile = "packageconfig.cxh"; // Path Profile Private string objPath = "D: // Work / / gDLT // src "; // Target File Path Private PrivateStream PS = NULL; // Output Message Redirect Private ArrayList Lines = NULL; // Save Profile String [] Heads = NULL; / / Save Each Configuration String globalline; // Record a configuration information / ** * Read a java file, return to his package information to take out * @Param File file handle * @returN return Package * / private string readpac (file file) {String Pac = NULL; try {buffredreader fr = new bufferedreader (new fileReader (file); string line = fr.readline (); while (line! = null) {// Processing the current row line.trim (); if (Line. StartSwith ("package")) {// found package PAC = line.substring (7, line.Length () - 1) .trim (); break;} line = fr.readline ();}} catch (ooException IE) {PAC = null; ie.printstacktrace ();} return pac;} / ** * Additional configuration files, such as sbzs: * @Param Line, a configuration file * @return * / private string gethead (String line) {Int POS = line.indexof (":"); if (POS == - 1) {ps.println ("Profile is wrong"); return "";} return line.substring (0, pos); / ** * reads the configuration file, the ArrayList and heads * @return * / private boolean readCfg (File cfgFile) {try {BufferedReader fr = new BufferedReader (new FileReader (cfgFile)); String line = fr.readLine (); While (line! = null) {// Processing the current line line.trim (); lines.add (line); line = fr.readline ();} int size = lines.size (); heads = new string [size ]; For (int i = 0; i Try {cfgfile.delete (); cfgfile.createNewFile (); bufferedwriter bw = new bufferedwriter; int size = lines.size (); for (int i = 0; i / ** * * Take the file from the Package message * @Param Pack Packet Path * @return Returns the file should return NULL to indicate the failure, you need to read, such as SBZS * and intelligent update configuration Document * / private string parse {string path = null; string line = null; try {for (int i = 0; i / ** * Copy the file to the full path to * @Param File file handle * @Param path file target absolute path * @return * / private boolean copy (file file, string fullpath) {ps.println (" Start copy file .... "); ps.println (" Source File: " file.getname ()); ps.println (" Target File: " FullPath; string filename = file.getname (); INT POS = filename.lastIndexof (file.separator); if (POS> 0) {filename = filename.substring (POS 1, filename.length ());} String lastpath = FULLPATH FILE.SEPARATOR FILENAME = New file (LastPath); if (objfile.exists () &&! objfile.delete ()) {// If there is, remove ps.println ("Delete Target Failed"); Return False;} // Start Copy Try {objFile.createNewFile (); FileInputStream fis = new FileInputStream (file); FileOutputStream fos = new FileOutputStream (objFile); byte [] buf = new byte [1024]; int i = 0; while ((i = fis.read ( BUF))! = - 1) {Fos.Write (buf, 0, i);} fis.close (); fos.close ();} catch (ioException ie) {ie.printstacktrace (); return false;} Return True; } / ** * Generate a configuration file * @Param PAC Package path * @param path file path * @return Returns to save whether it is correct * / public boolean createcfg () {file dir = new file (objPath); string [] DIRS = DIR. List (); string curdir; char SEP = file.seParatorChar; string line; for (int i = 0; i / ** * Judgment if a directory has a subdirectory, does not return true * @Param Dir * @return * / private boolean hasnosub (string directory) {file dir = new file (directory); if (! Dir.Indirectory ()) {Return True;} String [] Subs = dir.list (); for (int i = 0; i / ** * loop processing a folder * / public void excute () {char SEP = file.seParatorChar; file list = new file (filepath sep "list.txt"); file dir = new file (filepath); ifPath; (! DIR.EXISTS () ||! Dir.IsDirectory ()) {// Specify not a directory PS.Println ("Specify the directory of the upload file is incorrect"); return;} file cfgfile = new file (filepath sep configefile; try {printstream pslist = new version); if (! cfgfile.exists () &&! cfgfile.createNewFile ()) {// Profile does not exist ps.println ("specified configuration File does not exist "); return;} if (! Readcfg (cfgfile)) {// read configuration file failed ps.println (" Reading configuration file failed "); return;} file [] files = dir.listfiles ); If (files.Length <2) {// Does not to upload file ps.println ("There is no file in the specified directory"); return;} // Command FOR (INT i = 0; i Copy file failed " curfile.getname ()); Continue;} curfile.delete (); ps.println (" Successful Save One File ");} Ps.Println (" Successfully Solving All Files "); if (! Savecfg (cfgfile)) {ps.println ("Save Profile Failed"); Return;}} Catch (IOException IE {IE.PrintStackTrace ();}} / ** * Construction Function * / Public SaveFile () {Try { File log = new file (filepath file.separator "cf.log"); if (log.exists ()) {log.delete ();} log.createNewFile (); fileoutputstream fos = new fileoutputstream (log); ps = New PrintStream (FOS);} catch (ioException ie) {ie.printstacktrace (); system.out.print ("Create log failed!"); ps = system.out;} lines = new arraylist (); Public static void main (String [] args) {savefile sf = new savefile (); if (args.length == 1) {if (args [0] .Equals ("mc")) {// Generate a configuration file SF .createcfg ();} if (args [0]. Equals ("cf")) {// Complete classification copy work sf.excute ();}} else {sf.ps.println ("Please specify parameters: / n MC Generate Profile / N CF Copy File "); Return;}}} Cao Xihua is in 2005-15 13:11:29 Welcome to the letter. There is my contact information on the BLOG homepage.