Documentation Operations Development Guide

Source: Internet
Author: User
Tags documentation file url stringbuffer
Documentation Operations Development Guide 1 Revision History
Version Modify History Author Describe Development time (h)
0.1 2007-8-13 Levinsoft Basic structure, basic process for creating documents 2
2 IntroductionThis paper is a guide to the development of file-related operations, introduced the basic concept of the file, operating procedures, the use of APIs, using the specific code as an example. Most of these basic concepts are directly referenced by JDK documentation, and the relevant API usage is sorted and sorted. The paper presents some methods and techniques for cross system operation files, and finally introduces some Open-source file API projects and reference resources. 3 Basic ConceptsAn abstract representation of the file and directory path names. The user interface and operating system use a system-related pathname string to name the files and directories. This class renders an abstract, system-independent view of a hierarchical path name. The abstract pathname has two components: an optional system-related prefix string, such as a disk character, "/" for the root directory in UNIX, "////" for the Microsoft Windows UNC pathname, and a sequence of 0 or more string names. In addition to the last one, each name in the abstract pathname represents a directory, and the last name can represent either a directory or a file. An empty abstract pathname has no prefix and name sequence. The transformation between the path name string and the abstract pathname is system-related. When you convert an abstract pathname to a path name string, each name is separated from the next name by a single default separator character. The default name separator is defined by the system property File.separator, or from a public static field of this class Separator and Separatorchar. When you convert a pathname string to an abstract pathname, you can use either the default name separator or any other name delimiter supported by the underlying system to separate the name from it. Either an abstract path name or a string pathname, either an absolute path name or a relative path name. The absolute pathname is the full pathname, and you can locate the file that you represent without any additional information. Conversely, relative path names must be interpreted using information from other pathname. By default, classes in the Java.io package always parse the relative pathname based on the current user directory. This directory is specified by the system Properties User.dir, typically the invocation directory of the Java virtual machine. The concept of prefixes is used to handle the root directory of the UNIX platform, as well as the disk, root, and UNC pathname on the Microsoft Windows platform, as follows: For UNIX platforms, the prefix for absolute pathname is always "/". The relative path name has no prefix. The prefix that represents the absolute pathname of the root directory is "/" and there is no name sequence. For the Microsoft Windows platform, the prefix for the path name containing the letter is composed of a drive name and a ":": If the path name is an absolute pathname, the following may be followed by "//." The UNC pathname is prefixed with "////"; the host name and share name are the first two names in the name sequence. The relative path name of the drive is not specified without a prefix. Instances of the file class are immutable; that is, once created, the abstract path name represented by the file object never changes.4 basic operation of files 4.1 Common Types 4.1.1 RandomaccessfileInstances of this class support reading and writing to random-access files. Random-access files behave like a large byte array stored in the file system. There is a cursor or index pointing to the suppressed array, called a file pointer, and the input operation reads the byte from the file pointer and moves the file pointer forward as the byte is read. If a random access file is created in read/write mode, the output operation is also available; the output operation writes bytes from the file pointer and moves the file pointer forward as the byte is written. The output operation after writing the current end of the suppressed array causes the array to expand. The file pointer can be read through the Randomaccessfilepointer method and set by the Seek method. Typically, if all the read routines in this class have reached the end of the file before reading the desired number of bytes, the eofexception is thrown (a ioexception). If you cannot read any byte for some reason, instead of reaching the end of the file before reading the desired number of bytes, throw IOException instead of eofexception.     In particular, it is possible to throw a ioexception if the stream has been closed.     Randomaccessfile file = new Randomaccessfile (file, rw); File.seek (0);4.1.2 BufferedReaderReads text from a character input stream, buffers individual characters, and provides efficient reading of characters, arrays, and rows. Each read request made by reader usually results in a corresponding read request to the underlying character or byte stream. Therefore, it is recommended to use BufferedReader to wrap all Reader (such as FileReader and InputStreamReader) whose read () operation may be expensive.   For example, bufferedreader in = new BufferedReader (New FileReader ("foo.in")); The input of the specified file is buffered. If there is no buffering, each call to read () or readLine () causes the byte to be read from the file and returned after it is converted to a character, which is extremely inefficient.4.1.3 BufferedWriterContrary to the BufferedReader. BufferedWriter out = new BufferedWriter (New FileWriter ("Foo.out"));4.1.4 PrintWriterPrints the formatted representation of an object to the text output stream. This class implements all the print methods in the PrintStream. It does not contain methods for writing raw bytes, which should be written with an encoded stream of bytes. Unlike the PrintStream class, if automatic refresh is enabled, this can only be done when one of the methods of println, printf, or format is invoked, rather than when a new line character is just exported. These methods use the platform-owned line separator concept rather than the new line character. Methods in this class do not throw I/O exceptions, although some of their construction methods may throw exceptions. The client might query the calling CheckError () If there is an error.
PrintWriter out = new PrintWriter (new BufferedWriter) (New FileWriter ("Foo.out"));
4.1.5 Get System Properties
Systemutils is a practical class that is an API for Apache Commons. This class allows you to obtain system properties such as the Java_home,java version, some constant parameters, and so on.
4.1.6 File Upload 4.1.6.1 FileUpload class,It is Apache Commons an API that provides some way to upload.4.1.6.2 Smartupload classProvides file upload and download functions, from Jspsmartupload.jar. Smartupload smartupload =NewSmartupload (); Smartupload.initialize ( This.            servlet. Getservletconfig (), request,response); Smartupload.setcontentdisposition (NULL); Smartupload.downloadfile (LocalFile);4.1.7 webutilsis a tool class in spring. Miscellaneous utilities for Web applications. Used by various framework classes. For example: File tmpdir = Webutils.gettempdir (Servlet.getservletcontext ());4.2 Load File Method1. Get file URL by Class (Filter.getclass (). GetResource ("Songs.xml"). Randomaccessfile ()); 2. Obtains Java.io.InputStream ConfigUtils.class.getResourceAsStream ("Song.xml") through class;4.3 operation file Instances 4.3.1 export files to local directory private void Exportmessage (StringBuffer stringbuffer,string localdir)      {   & nbsp;     file Errfile=new file (localdir+systemutils.file_separator+batchid+ ". txt");          try          {               if (errfile.exists ())                {                    Errfile.delete ();              }                Errfile.createnewfile ();              PrintWriter outprint = new PrintWriter (new BufferedWriter (New FileWriter (Errfile));              outprint.println (StringBuffer);              Outprint.flush ();         }          catch ( IOException e)          {               logger.debug ("Export Error file failed:" +e);               throw new Daoexception ("Export Error file failed:" + e.getmessage ());         }     }    4.3.2            ways to delete files and folders private void Deletetempfile (String fileName) {      //Get temporary files in folder         file Folder = new file (fileName). Getparentfile ();        if (folder.exists ()) {           //delete all files under folder            for (int i = 0; i < Folder.listfile S (). length; i++) {              File File = Folder.listfiles () [i];               if (!file.delete ()) {                   logger.debug ("file" + File.getname () + "Delete failed");              }            } &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp; //Delete folder            Folder.Delete ();       }    }5 manipulating files on FTP 5.1 Common class bagsApache Commons Network Pack: Apache commons-net-1.3.0 provides the FTP operation API, the common classes are: 1. FtpClient provides a common way to access FTP server, such as: Connection, upload, download, and so on. Example: FtpClient ftpclient =getconnect (path, host, username, password);5.2 Download File Instances 5.2.1 Download Process public static void DownloadFile (String localefile, String remotefile, String path, string host,     & nbsp;             string Username, string password) throws Serviceexception     {       try        {           ftpclient client  = getconnect (path, host, Username, password);                        file = new file (localefile);              Randomaccessfile  randomaccessfile = new Randomaccessfile (file, "RW");            randomaccessfile.seek (0);                        telnetinputsTream fget = Client.get (remotefile);                        DataInputStream  puts = new DataInputStream (fget);            while (int ch = puts.read ()) >= 0)             {               randomaccessfile.write (CH);           }       }         catch (FileNotFoundException ex)        {            Ex.printstacktrace ();            throw new Serviceexception ("Please verify that the file exists.") ");       }        catch (IOException ex)         {           ex.printstacktrace ();             throw new Serviceexception ("file read exception", ex);       }        finally{                       try {               if (fget!=null)                    Fget.close ();               if (randomaccessfile!=null)                    Randomaccessfile.close ();               if (client!=null)                    Client.closeserver ();            catch (IOException e) {               throw new Serviceexception ("Flow off exception", e);           }                   }    }API recommended for use by 5.2.2Operation files, recommend the use of PrintWriter, BufferedWriter, filewriter packaging, simplified operation. For example: printwriter out = new PrintWriter (new BufferedWriter (New FileWriter ("Foo.out")); If there is no buffering, each call to the print () method causes the character to be converted to bytes and then written to the file immediately, which is extremely inefficient.6 summary and ProspectA simple summary of the previous knowledge B) the future improvement part7 reference materials1. The Apache commons related jar packages and reference documentation.8 Terminology and appendices

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.