Java file Operations

Source: Internet
Author: User

The Java.io package provides a large number of stream classes, where all input streams are subclasses of the InputStream abstract class (byte input stream) and Reader abstract class (character input stream), and all output streams are outputstream abstract classes (byte output streams) and writer abstract classes ( The subclass of the character output stream).

File class: (Processing files and directories)
The file object mainly obtains the properties of the files themselves, such as file directory, file length, and file read/write permissions, and does not involve read and write operations on the contents of the file.
There are three construction methods for creating a file object:
File (String filename)
File (string directorypath, string filename)
File (file F, String filename)//f is a document that formulates a directory

Properties of the file:
Often the file class uses the following methods to obtain some information about the files themselves:
Public String GetName ()//Get file name
public boolean CanRead ()//Determine if the file is readable
public boolean canWrite ()//Determine if the file is writable
public Boolean exists ()//Determine if the file exists
public long Length ()//Get file Length (bytes units)
Public String GetAbsolutePath ()//Get File absolute path
Public String getParent ()//Get File parent directory
public boolean isfile ()//Determine if the file is a normal file, not a directory
public boolean isdirectory ()//Determine if the file is an (already existing) directory
public boolean Ishidden ()//Determine if the file is a hidden file
Public long lastmodified ()//Gets the last modified time of the file (the time is the number of milliseconds from midnight 1970 to the last modified time of the file)

Directory:
1. Create a directory:
Use the file object to invoke the method public boolean mkdir () to create a directory that successfully creates returns true, otherwise returns False (False if the directory already exists).

2. List the files in the directory:
If the file object is a directory, the object can call the following methods to list the files and subdirectories in that directory.
Public string[] List ()//return all files in the directory as a string
Public file[] Listfiles ()//Return all files in directory as file object

File filter:
Sometimes you need to list the specified type of file under the directory, you can use the two methods of the file class, as follows:,
Public string[] List (FilenameFilter obj)
Public file[] Listfiles (FilenameFilter obj)
FilenameFilter is an interface that has a method:
Public Boolean Accept (File dir, String name)
When you use the list method, you want the method to pass an object that implements the FilenameFilter interface. When the list method executes, the parameter is constantly callback to the interface method accept (file dir, String name), the parameter name is a file name of the instantiated directory, and the dir is the current directory of the call list, and when the interface method returns True, the The list method stores the files in the directory dir in the returned array.

  Example: (Lists all Java file names in the current directory)
  import java.io.*;
  public class Test1 {
   public test1 () {
   //TODO automatically generate constructor stub
   }
   public static void Main (string[] args) {
    file dir = new File (".");   //system "." Represents the current directory, "..." Represents the current top level directory, ("\" is the root directory, but is represented as "\ \" for escape)
    fileaccept acceptcondition = new Fileaccept ("Java");
    string[] FileName = dir.list (acceptcondition);
    for (int i=0; i<filename.length; i++) {
      System.out.println (Filename[i]);
    }
   }
  }

public class Fileaccept implements FilenameFilter {
String str = NULL;
Public fileaccept (String s) {
TODO automatically generates constructor stubs
str = "." +s;
}
Public Boolean Accept (File dir, String name) {
TODO automatically generate method stubs
return Name.endswith (str);
}
}




File creation and deletion: (example below)
File F = new file ("c:\\", "Letter.dat"); First, create a file object with the files class.
if (!f.exists ()) {//If the file is not in this folder, create a new
try{
F.createnewfile ();
}
catch (IOException e) {
}
}

if (f.exists ()) {//If the file is present, delete it. You can also use the F.deleteonexit () method between.
F.delete ();
}


Run the executable file:
To run an executable file, use the Java.lang.Runtime class.
Declare an object with the runtime class first, such as:
Runtime run;
This object is then created with the class method of the Class GetRuntime (), such as:
Run = Runtime.getruntime ();
Where run can call the EXEC (String command) method to open an executable file on the local machine or perform an operation.
Examples are as follows:
try{
Runtime run = Runtime.getruntime ();
File File = new file ("C:\\Windows", "Notepad.exe");
Run.exec (File.getabsolutepath ());
}
catch (Exception e) {
System.out.println (e);
}


  byte input and output stream classes: (FileInputStream class and FileOutputStream Class)
  when file read requirements are relatively simple, use the FileInputStream class, The class is derived from the InputStream class.
 fileinputstream Class Common methods of construction two:
  fileinputstream (String name)   // Creates a FileInputStream object with the given filename name,
  fileinputstream (file file)   // Create a FileInputStream object using the file object

  Read the file using the FileInputStream file input stream object, as an example:
  fileinputstream istream = new FileInputStream (" Hello.txt ");
  or
  file file = new file ("Hello.txt");
  fileinputstream istream = new FileInputStream (file);
 
  Handling I/O Exceptions:
  Using the file input stream construction method to create an object may be an error, such as the file to be opened does not exist, etc., use the IOException object to represent this error signal. The program must capture to handle this exception. This is similar to the following:
  try {
   fileinputstream istream = new FileInputStream ("Hello.txt");
  }
  catch (IOException e) {
   system.out.println ("File read error:" +e);   
  }
  (I/O operations are particularly sensitive to errors, and all of the construction and read-write methods of many stream classes cause I/O exceptions, which the program must capture to handle. )

Read bytes from the input stream:
The input stream calls the read () method and reads the data from the input stream. Here's how:
int read (); Sequentially reads a single byte of data from the source, returns a byte value (0-255 integers), and returns 1 if it reaches the end of the source.
int read (byte b[]); Reads b.length bytes, stored in array B, and returns the number of bytes actually read.
int read (byte b[], int off, int len)//reads Len bytes, is stored in array B, and off is the position of the first byte in the array, returning the actual number of bytes read.
(The Read () method reads the file sequentially, as long as the stream does not close, each time the read () method is called, the rest of the source is read sequentially until the end of the source or the stream is closed!)

To close a stream:
It is a good practice to close it with a stream, although Java automatically closes all open streams at the end of the program. Because an open stream may exhaust system resources, this depends on the platform and implementation. If you do not close a stream that is open, you may not allow another program to manipulate the resources used by those streams. Another reason to turn off the output stream is to ensure that the operating system writes data from the stream buffer to the disk (destination).
You can use the file input/output stream object to call the close () method to close the stream.


The FileOutputStream class corresponds to the FileInputStream class. The construction method and its use are consistent with Fileoinputstream.
You can use the output stream object to call the Write method to write bytes to the output stream and reach the destination. As follows:
public void Write (int b)//writes the specified bytes to the output stream
public void Write (Byte b[])//write B.length bytes to an output stream
public void Write (byte b[], int off, int len)//writes Len bytes from byte array b starting at offset off to output stream
(The FileOutputStream stream writes the file sequentially, as long as the stream is not closed, each time the write () method is called, the data is written sequentially to the output stream until the stream is closed!)


Character input and output stream class: (FileReader class and FileWriter Class)
byte input and output stream classes read and write data in byte units and do not operate well with Unicode characters. If you use a character stream, you are not prone to garbled problems.
FileReader and FileWriter are sub-classes of reader and writer, and are constructed as follows:
FileReader (String name); FileReader (file file);
FileWriter (String name); FileWriter (file file);

The read () and write () methods of the

  character input/output stream use character arrays to read and write data, with characters (char) as the basic unit. Common methods are as follows:
  int read ()   //reads a character from the source, returns a Unicode character value (0-65535 integers), and the unread character returns-1.
  int Read (char b[])  
  int Read (char b[], int off, int len)
  void Write ( int n)   //writes a character (Unicode character value) to the destination
  void write (char b[])
  void write (char b[], int off, int len)


 bufferedreader class and BufferedWriter class:
  When you need to read and write one line at a time, you cannot know how many characters a line has, that is, the size of the character array cannot be determined, FileReader It is difficult to accomplish such a task in the FileWriter class. This can be done with the BufferedReader and BufferedWriter streams in the
 java. Both the source and destination must be a character input stream and a character output stream. Therefore, Reader (character input stream) can be used as the source of the BufferedReader stream, and writer (character output stream) stream as the destination of the BufferedWriter stream.
  Constructs the following method:
  bufferedreader (Reader in);
  bufferedwriter (Writer out);
  Use the BufferedReader class object to call the ReadLine () method to read the text line:
  filereader filereader = new FileReader (" Student.txt ");
  bufferedreader in = new BufferedReader (FileReader);
  string strLine = In.readline ();

  Similarly, you can connect the BufferedWriter stream with the FileWriter stream, and then use the BufferedWriter stream to write the data to the destination, such as:
  filewriter FileWriter = new FileWriter ("Student.txt");
  bufferedwriter out = new BufferedWriter (filewriter);
  Then outputs a method that uses the BufferedWriter class, such as:
  write (String s, int off, int len)   // Writes the string s to Student.txt, off is the offset at the beginning of S, and Len is the number of characters written.
 
  BufferedReader and BufferedWriter can be called the upper stream, and the stream of characters they point to is called the underlying stream. Java uses caching techniques to connect the upper and lower streams. The underlying character input stream reads the data into the cache first, the BufferedReader stream then reads the data from the cache, the BufferedWriter stream writes the data to the cache, and the underlying character output stream continuously writes the data from the cache to the destination.
  when the BufferedWriter stream calls the Flush () method to flush the cache or call the close () method to close, the underlying stream will immediately write the cached data to the destination, even if the cache is not overflowing.


Randomaccessfile class:
Java provides a more complete Randomaccessfile stream for handling file input and output operations, which can be directed either as a source or as a destination, that is, when reading and writing a file, create a randomaccessfile stream that points to the file.
Randomaccessfile Class Two construction methods:
Randomaccessfile (string name, string mode)//mode R (read-only) or RW (Readable and writable)
Randomaccessfile (file file, String mode)//mode R (read-only) or RW (Readable and writable)

There is a method in the Randomaccessfile class seek (long a) to locate the read and write position of the Randomaccessfile stream, and parameter a determines the number of bytes from the beginning of the file to the read and write location. You can also call the Getfilepointer () method to get the current read and write location of the stream. Randomaccessfile Stream is more flexible to read and write files than sequential read and write!
(There are many ways to see the JDK in detail.)


Data flow: (DataInputStream and DataOutputStream classes)
The data input stream and the data output stream allow the program to read Java raw data in a machine-independent style. That is, when reading a numeric value, you do not have to worry about how many bytes this value should be.
Construction Method:
DataInputStream (InputStream in)//the data input stream to be created points to a bottom input stream specified by in
DataInputStream (OutputStream out)//the data output stream to be created points to a lower-level output stream specified by out
(This flow class is amazing!) Java does provide a lot of advanced tools that C + + programmers crave, check out the JDK in detail.


Input stream with progress bar:
The read progress of a file can be seen when the file is read using the input stream created by the Javax.swing.ProgressMonitorInputStream class.
The construction method is as follows:
Progressmonitorinputstream (Component C, Object message, inputstream in)//progress bar is displayed directly in front of C specified component, if NULL, is displayed in front of the screen, message specifies the display information on the progress bar (String)
Examples are as follows:
Import javax.swing.*;
Import java.io.*;
Import java.awt.*;
Import java.awt.event.*;
public class Test1 {
public static void Main (string[] args) {
byte b[] = new BYTE[2];
JTextArea Text = new JTextArea (20,20);
JFrame JFrame = new JFrame ();
Jframe.setsize (280,300);
Jframe.setvisible (TRUE);
Jframe.setdefaultcloseoperation (Jframe.exit_on_close);
Jframe.add (new JScrollPane (text), borderlayout.center);
Jframe.validate ();
try{
FileInputStream input = new FileInputStream ("Test1.java");
Progressmonitorinputstream input_progress = new Progressmonitorinputstream (JFrame, "read Java file", input);
Progressmonitor p = input_progress.getprogressmonitor ();
while (Input_progress.read (b)! = 1) {
string s = new string (b);
Text.append (s);
Thread.Sleep (10);
}
}
catch (Exception e) {}
}
}


Object flow: (ObjectInputStream and Objectoutputsteam classes)
The ObjectInputStream (object input stream) and Objectoutputsteam (object output stream) classes are subclasses of the InputStream and OutputStream classes, respectively.
The ObjectInputStream object calls the ReadObject () method to read an object into the program, and the ObjectOutputStream object calls the Writerobject (object obj) method to write an object obj to a file.
The two classes are constructed in the following way:
ObjectInputStream (InputStream in)//in an input stream object created for a subclass of InputStream
Objectoutputsteam (OutputStream out)//out an output stream object created for a subclass of OutputStream

When using object flow, make sure that the object is serialized. This is to ensure that the object can be written to the file and read back to the program properly.
A class implements the Serializable interface, which creates objects that are serialized. (The methods in the serializable interface are not visible to the program and are implemented automatically by the JVM, so implementing the interface does not require additional methods.) Note, however, that when you use object flow to write an object to a file, in addition to ensuring that the object is serialized, the object's member object must also be serialized. )

Example:
Import java.io.*;
public class Student implements Serializable {
String name = NULL;
Double height;
Public Student (String name, double height) {
TODO automatically generates constructor stubs
THIS.name = name;
This.height = height;
}
public void SetHeight (double c) {
This.height = C;
}
}
public class Test1 {
public static void Main (string[] args) {
Student Zhang = new Student ("Zhang San", 1.65);
try{
FileOutputStream file_out = new FileOutputStream ("S.txt");
ObjectOutputStream object_out = new ObjectOutputStream (file_out);
Object_out.writeobject (Zhang);

FileInputStream file_in = new FileInputStream ("S.txt");
ObjectInputStream object_in = new ObjectInputStream (file_in);
Student li = (Student) object_in.readobject ();
Li.setheight (1.78);
Li.name = "John Doe";
System.out.println (zhang.name+ "height is:" +zhang.height);
System.out.println (li.name+ "height is:" +li.height);
}
catch (ClassNotFoundException event) {
SYSTEM.OUT.PRINTLN ("Cannot read out objects");
}
catch (IOException event) {
System.out.println ("Can not read file" +event);
}
}
}


Serialization and object cloning:
Two objects of a class have the same entity and functionality if they have the same reference. Such as:
A one = new A ();
A and one;
This action on the one member variable will change the member variable in two (two entities are the same).

Call the Clone () method if you want the object's cloned object (the clone object changes without causing the original object to change). (Note: If the source object has a reference member variable, it involves a deep-clone problem, overriding the Clone () method, similar to a dark copy in C + +.) )
Using object flow makes it easy to get a clone of a serialized object. (Because the object written to the object's output stream points to the object that is read back must be a clone of the original object)

Specifically write a class that uses object input and output streams to clone objects:
Import java.io.*;
public class Getcloneobject {
public object Getclone (object obj) {
Object object = null;
try{
FileOutputStream file_out = new FileOutputStream ("Serialization information for the object. txt");
ObjectOutputStream object_out = new ObjectOutputStream (file_out);
Object_out.writeobject (obj);

FileInputStream file_in = new FileInputStream ("Serialization information for the object. txt");
ObjectInputStream object_in = new ObjectInputStream (file_in);
Object = Object_in.readobject ();
}
catch (Exception event) {
System.out.println (event);
}
return object;
}
}

Most of the objects provided by Java are serialized. such as the Stringbuffer,component class, they all implement the serializable interface. You can write the component to the output stream, and then read the clone of the component with the input stream.
The following example:
Import java.awt.*;
Import java.awt.event.*;
Import javax.swing.*;
public class Mywin extends JFrame implements ActionListener {
JTextArea text = null;
JButton button;
Getcloneobject Cloneobject;
Public Mywin () {
TODO automatically generates constructor stubs
SetLayout (New FlowLayout ());
Cloneobject = new Getcloneobject ();
Text = new JTextArea (6,10);
button = new JButton ("Get clone of text area");
Button.addactionlistener (this);
SetVisible (TRUE);
Add (new JScrollPane (text));
Add (button);
SetSize (580,300);
Validate ();
Setdefaultcloseoperation (Jframe.exit_on_close);
}
public void actionperformed (ActionEvent e) {
TODO automatically generate method stubs
JTextArea Textclone = (jtextarea) cloneobject.getclone (text);
Textclone.setbackground (Color.pink);
This.add (New JScrollPane (Textclone));
This.validate ();
}

}

public class Test1 {
public static void Main (string[] args) {
Mywin win = new Mywin ();
}
}


File Lock: (Filelock and FileChannel Class)
Java.nio.FileLock and Java.nio.channels.FileChannel classes. Input, the output stream can be used to read and write files with a file lock, the stream created with the Randomaccessfile class can use a file lock when reading and writing files, as long as the lock is not unlocked, other threads cannot manipulate the locked file.
(1), using Randomaccessfile stream to establish a stream object pointing to the file (the read-write property must be RW):
Randomaccessfile input = new Randomaccessfile ("Hello.java", "RW");
(2), Stream object Input Method Getchannel () obtains a FileChannel object (channel) connected to the underlying file:
FileChannel channel = Input.getchannel ();
(3), channel call Trylock () or lock () method to obtain a Filelock (file Lock) object, this process is called to lock the file:
Filelock lock = Channel.trylock ();
After the file lock object is created, no program is allowed to manipulate or lock the file. If you want to do this, you must first let the Filelock object call the release () method to release the file lock:
Lock.release ();


Java file Operations

Related Article

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.