After work, the technology used changes with the change of the project, sometimes C #, sometimes Java, and of course there are other fragmented technologies. In general, the use of C # takes longer, followed by Java. I have no preference for language. A language that can work is a good language. In addition, from the object-oriented perspective, I think C # and Java are no different for me.
This article mainly reviews the content related to I/O operations in Java. I/O is also a basic feature of programming languages. I/O in Java is divided into two types, one is sequential reading, and the other is random reading.
First, let's look at sequential reading. There are two methods for sequential reading. One is InputStream/OutputStream, which is the input and output stream for byte operations; the other is Reader/Writer, which is an input/output stream for character operations.
Next we will plot the structure of InputStream.
FileInputStream: Operation file, often used with BufferedInputStream
PipedInputStream: used for inter-thread communication.
ObjectInputStream: used for Object serialization
ByteArrayInputStream: used to process input of byte Arrays
LineNumberInputStream: outputs the current number of rows and can be modified in the program.
The structure of OutputStream is as follows:
PrintStream: provides APIs similar to print and println to output data.
The following describes how to use Stream to operate input and output.
Use InputStream to read files
Copy codeThe Code is as follows: Use FileInputStream To Read File Information
Public static byte [] readFileByFileInputStream (File file) throws IOException
{
ByteArrayOutputStream output = new ByteArrayOutputStream ();
FileInputStream FCM = null;
Try
{
FS = new FileInputStream (file );
Byte [] buffer = new byte [1024];
Int bytesRead = 0;
While (bytesRead = Fi. read (buffer, 0, buffer. length ))! =-1)
{
Output. write (buffer, 0, bytesRead );
}
}
Catch (Exception ex)
{
System. out. println ("Error occurs during reading" + file. getAbsoluteFile ());
}
Finally
{
If (FS! = Null) FCM. close ();
If (output! = Null) output. close ();
}
Return output. toByteArray ();
}
Use BufferedInputStream to read filesCopy codeThe Code is as follows: public static byte [] readFileByBufferedInputStream (File file) throws Exception
{
FileInputStream FCM = null;
BufferedInputStream bis = null;
ByteArrayOutputStream output = new ByteArrayOutputStream ();
Try
{
FS = new FileInputStream (file );
Bis = new BufferedInputStream (FCM );
Byte [] buffer = new byte [1024];
Int bytesRead = 0;
While (bytesRead = bis. read (buffer, 0, buffer. length ))! =-1)
{
Output. write (buffer, 0, bytesRead );
}
}
Catch (Exception ex)
{
System. out. println ("Error occurs during reading" + file. getAbsoluteFile ());
}
Finally
{
If (FS! = Null) FCM. close ();
If (bis! = Null) bis. close ();
If (output! = Null) output. close ();
}
Return output. toByteArray ();
}
Use OutputStream to copy filesCopy codeThe Code is as follows: Use FileOutputStream to copy an object
Public static void copyFileByFileOutputStream (File file) throws IOException
{
FileInputStream FCM = null;
FileOutputStream fos = null;
Try
{
FS = new FileInputStream (file );
Fos = new FileOutputStream (file. getName () + ". bak ");
Byte [] buffer = new byte [1024];
Int bytesRead = 0;
While (bytesRead = Fi. read (buffer, 0, buffer. length ))! =-1)
{
Fos. write (buffer, 0, bytesRead );
}
Fos. flush ();
}
Catch (Exception ex)
{
System. out. println ("Error occurs during copying" + file. getAbsoluteFile ());
}
Finally
{
If (FS! = Null) FCM. close ();
If (fos! = Null) fos. close ();
}
}
Copy codeThe Code is as follows: Use BufferedOutputStream to copy an object
Public static void copyFilebyBufferedOutputStream (File file) throws IOException
{
FileInputStream FCM = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Try
{
FS = new FileInputStream (file );
Bis = new BufferedInputStream (FCM );
Fos = new FileOutputStream (file. getName () + ". bak ");
Bos = new BufferedOutputStream (fos );
Byte [] buffer = new byte [1024];
Int bytesRead = 0;
While (bytesRead = bis. read (buffer, 0, buffer. length ))! =-1)
{
Bos. write (buffer, 0, bytesRead );
}
Bos. flush ();
}
Catch (Exception ex)
{
System. out. println ("Error occurs during copying" + file. getAbsoluteFile ());
}
Finally
{
If (FS! = Null) FCM. close ();
If (bis! = Null) bis. close ();
If (fos! = Null) fos. close ();
If (bos! = Null) bos. close ();
}
}
The code here is very incomplete in exception handling. We will provide complete and rigorous code later.
Let's take a look at the Reader structure.
Here, the Reader basically corresponds to InputStream.
The Writer structure is as follows:
Here are some examples of using Reader or Writer.
Use Reader to Read File Content
Copy codeThe Code is as follows: Use BufferedReader to read the file content
Public static String readFile (String file) throws IOException
{
BufferedReader br = null;
StringBuffer sb = new StringBuffer ();
Try
{
Br = new BufferedReader (new FileReader (file ));
String line = null;
While (line = br. readLine ())! = Null)
{
Sb. append (line );
}
}
Catch (Exception ex)
{
System. out. println ("Error occurs during reading" + file );
}
Finally
{
If (br! = Null) br. close ();
}
Return sb. toString ();
}
Use Writer to copy filesCopy codeThe Code is as follows: Use BufferedWriter to copy a file
Public static void copyFile (String file) throws IOException
{
BufferedReader br = null;
BufferedWriter bw = null;
Try
{
Br = new BufferedReader (new FileReader (file ));
Bw = new BufferedWriter (new FileWriter (file + ". bak "));
String line = null;
While (line = br. readLine ())! = Null)
{
Bw. write (line );
}
}
Catch (Exception ex)
{
System. out. println ("Error occurs during copying" + file );
}
Finally
{
If (br! = Null) br. close ();
If (bw! = Null) bw. close ();
}
}
The following describes how to perform random access to files. in Java, RandomAccessFile is used to perform random operations on files.
Create a fixed-size file
Copy codeThe Code is as follows: Create a fixed-size file
Public static void createFile (String file, int size) throws IOException
{
File temp = new File (file );
RandomAccessFile raf = new RandomAccessFile (temp, "rw ");
Raf. setLength (size );
Raf. close ();
}
Randomly write data to a fileCopy codeThe Code is as follows: insert data randomly into the file
Public static void writeFile (String file, byte [] content, int startPos, int contentLength) throws IOException
{
RandomAccessFile raf = new RandomAccessFile (new File (file), "rw ");
Raf. seek (startPos );
Raf. write (content, 0, contentLength );
Raf. close ();
}
Next, let's look at some other common operations.
Move files
Copy codeThe Code is as follows: Move a file
Public static boolean moveFile (String sourceFile, String destFile)
{
File source = new File (sourceFile );
If (! Source. exists () throw new RuntimeException ("source file does not exist .");
File dest = new File (destFile );
If (! (New File (dest. getPath (). exists () new File (dest. getParent (). mkdirs ();
Return source. renameTo (dest );
}
Copy a fileCopy codeThe Code is as follows: copy an object
Public static void copyFile (String sourceFile, String destFile) throws IOException
{
File source = new File (sourceFile );
If (! Source. exists () throw new RuntimeException ("File does not exist .");
If (! Source. isFile () throw new RuntimeException ("It is not file .");
If (! Source. canRead () throw new RuntimeException ("File cound not be read .");
File dest = new File (destFile );
If (dest. exists ())
{
If (dest. isDirectory () throw new RuntimeException ("Destination is a folder .");
Else
{
Dest. delete ();
}
}
Else
{
File parentFolder = new File (dest. getParent ());
If (! ParentFolder. exists () parentFolder. mkdirs ();
If (! ParentFolder. canWrite () throw new RuntimeException ("Destination can not be written .");
}
FileInputStream FCM = null;
FileOutputStream fos = null;
Try
{
FCM = new FileInputStream (source );
Fos = new FileOutputStream (dest );
Byte [] buffer = new byte [1024];
Int bytesRead = 0;
While (bytesRead = Fi. read (buffer, 0, buffer. length ))! =-1)
{
Fos. write (buffer, 0, bytesRead );
}
Fos. flush ();
}
Catch (IOException ex)
{
System. out. println ("Error occurs during copying" + sourceFile );
}
Finally
{
If (FS! = Null) FCM. close ();
If (fos! = Null) fos. close ();
}
}
Copy a folderCopy codeThe Code is as follows: copy a folder
Public static void copyDir (String sourceDir, String destDir) throws IOException
{
File source = new File (sourceDir );
If (! Source. exists () throw new RuntimeException ("Source does not exist .");
If (! Source. canRead () throw new RuntimeException ("Source cocould not be read .");
File dest = new File (destDir );
If (! Dest. exists () dest. mkdirs ();
File [] arrFiles = source. listFiles ();
For (int I = 0; I <arrFiles. length; I ++)
{
If (arrFiles [I]. isFile ())
{
BufferedReader reader = new BufferedReader (new FileReader (arrFiles [I]);
BufferedWriter writer = new BufferedWriter (new FileWriter (destDir + "/" + arrFiles [I]. getName ()));
String line = null;
While (line = reader. readLine ())! = Null) writer. write (line );
Writer. flush ();
Reader. close ();
Writer. close ();
}
Else
{
CopyDir (sourceDir + "/" + arrFiles [I]. getName (), destDir + "/" + arrFiles [I]. getName ());
}
}
}
Delete folderCopy codeThe Code is as follows: delete a folder
Public static void del (String filePath)
{
File file = new File (filePath );
If (file = null |! File. exists () return;
If (file. isFile ())
{
File. delete ();
}
Else
{
File [] arrFiles = file. listFiles ();
If (arrFiles. length> 0)
{
For (int I = 0; I <arrFiles. length; I ++)
{
Del (arrFiles [I]. getAbsolutePath ());
}
}
File. delete ();
}
}
Get the folder sizeCopy codeThe Code is as follows: Get the folder size
Public static long getFolderSize (String dir)
{
Long size = 0;
File file = new File (dir );
If (! File. exists () throw new RuntimeException ("dir does not exist .");
If (file. isFile () return file. length ();
Else
{
String [] arrFileName = file. list ();
For (int I = 0; I <arrFileName. length; I ++)
{
Size + = getFolderSize (dir + "/" + arrFileName [I]);
}
}
Return size;
}
Split a large file into multiple small filesCopy codeThe Code is as follows: Split a large file into multiple small files.
Public static void splitFile (String filePath, long unit) throws IOException
{
File file = new File (filePath );
If (! File. exists () throw new RuntimeException ("file does not exist .");
Long size = file. length ();
If (unit> = size) return;
Int count = size % unit = 0? (Int) (size/unit): (int) (size/unit) + 1;
String newFile = null;
FileOutputStream fos = null;
FileInputStream FCM = null;
Byte [] buffer = new byte [(int) unit];
FS = new FileInputStream (file );
Long startPos = 0;
String countFile = filePath + "_ Count ";
PrintWriter writer = new PrintWriter (new FileWriter (new File (countFile )));
Writer. println (filePath + "\ t" + size );
For (int I = 1; I <= count; I ++)
{
NewFile = filePath + "_" + I;
StartPos = (I-1) * unit;
System. out. println ("Creating" + newFile );
Fos = new FileOutputStream (new File (newFile ));
Int bytesRead = FS. read (buffer, 0, buffer. length );
If (bytesRead! =-1)
{
Fos. write (buffer, 0, bytesRead );
Writer. println (newFile + "\ t" + startPos + "\ t" + bytesRead );
}
Fos. flush ();
Fos. close ();
System. out. println ("StartPos:" + I * unit + "; EndPos:" + (I * unit + bytesRead ));
}
Writer. flush ();
Writer. close ();
FCM. close ();
}
Merge multiple small files into a large fileCopy codeThe Code is as follows: Merge multiple small files into a large file
Public static void linkFiles (String countFile) throws IOException
{
File file = new File (countFile );
If (! File. exists () throw new RuntimeException ("Count file does not exist .");
BufferedReader reader = new BufferedReader (new FileReader (file ));
String line = reader. readLine ();
String newFile = line. split ("\ t") [0];
Long size = Long. parseLong (line. split ("\ t") [1]);
RandomAccessFile raf = new RandomAccessFile (newFile, "rw ");
Raf. setLength (size );
FileInputStream FCM = null;
Byte [] buffer = null;
While (line = reader. readLine ())! = Null)
{
String [] arrInfo = line. split ("\ t ");
FS = new FileInputStream (new File (arrInfo [0]);
Buffer = new byte [Integer. parseInt (arrInfo [2])];
Long startPos = Long. parseLong (arrInfo [1]);
FS. read (buffer, 0, Integer. parseInt (arrInfo [2]);
Raf. seek (startPos );
Raf. write (buffer, 0, Integer. parseInt (arrInfo [2]);
FCM. close ();
}
Raf. close ();
}
Execute External commandsCopy codeThe Code is as follows: Execute External commands
Public static void execExternalCommand (String command, String argument)
{
Process process = null;
Try
{
Process = runtime.getruntime(cmd.exe c (command + "" + argument );
InputStream is = process. getInputStream ();
BufferedReader br = new BufferedReader (new InputStreamReader (is ));
String line = null;
While (line = br. readLine ())! = Null)
{
System. out. println (line );
}
}
Catch (Exception ex)
{
System. err. println (ex. getMessage ());
}
Finally
{
If (process! = Null) process. destroy ();
}
}