Learning Essentials
- File class manipulating the properties of files and directories
- BYTE stream read-write file
- Character stream read and write files
- BYTE stream read-write binary file
Definition of file operation 1 file
A file can be thought of as a collection of related records or data that is put together. Files are generally saved in the media of hard disks, USB drives, CDs, and cloud disks.
2 How Java operates files
JAVA API:java.io.File Class
3 File Object Construction
File File = new file (String pathname);//string pathname format: "e:\\test. txt" or "e:/test. txt"
4 Common methods for file classes
Method name |
Description |
Boolean exists () |
Determine if a file or directory exists |
Boolean isfile () |
Determine if it is a file |
Boolean isdirectory () |
Determine if it is a directory |
String GetPath () |
Returns the relative path name of the file represented by this object |
String GetAbsolutePath () |
Returns the absolute path name of the file represented by this object |
String GetName () |
Returns the name of the file or directory represented by this object |
Boolean Delete () |
Delete the file or directory specified by this object |
Boolean CreateNewFile () |
Create an empty file with a name and do not create a folder |
Long Length () |
Returns the length of the file, in bytes, or 0L if the file does not exist |
5 Example file Operation files
public static void Main (string[] args) {fileoperation fm = new FileOperation (); File file = null; File = new file ("E:\\mydoc\\test.txt"); Fm.create (file); Fm.showfileinfo (file); Fm.delete (file); /** the method of creating the file */public void Create (file file) {if (!file.exists ()) {try {file}. CreateNewFile (); System.out.println ("The file has been created! "); } catch (IOException e) {e.printstacktrace (); }}}/** Delete file */public void Delete (file file) {if (file.exists ()) {file.delete (); System.out.println ("The file has been deleted! "); }}/** Displays the file information */public void Showfileinfo (file file) {if (file.exists ()) {///determine if the file exists if (f Ile.isfile ()) {//If it is a file System.out.println ("Name:" + file.getname ()); SYSTEM.OUT.PRINTLN ("Relative path:" + File.getpath ()); SYSTEM.OUT.PRINTLN ("absolute path:" + File.getaBsolutepath ()); SYSTEM.OUT.PRINTLN ("File size:" + file.length () + "byte"); } if (File.isdirectory ()) {System.out.println ("This file is a directory"); }} else System.out.println ("file does not exist"); }
6 on-Machine exercises
View file properties, create and delete files.
Stream 1 Definition
The Flie class provides methods for accessing file and directory properties, and how to read and write the contents of a file. Read and write through streams.
Flow concept: A stream is a series of characters flowing, which is a channel for sending information in FIFO mode.
The relationship between the input/output stream and the data source:
2 Classification of Java streams
- The input and output stream is relative to the computer's memory
- A byte stream is a 8-bit universal byte stream, which is a 16-bit Unicode character stream
- IO system
3 commonly used file reading and writing classes
Read and write text files
Byte stream mode: FileInputStream, FileOutputStream
Character Stream mode: BufferedReader, BufferedWriter
Read and write binary files
DataInputStream, DataOutputStream
Byte stream reading and writing 1 FileInputStream read text file
Common methods of InputStream class
Method |
description |
< P>int read () |
Reads a data byte from this input stream. |
int read (byte[] b) |
reads up to b.length bytes of data from this input stream into a byte array. |
int read (byte[] b,int off,int len) |
reads up to len bytes of data from this input stream into a byte array. |
Void Close () |
Close this article Input stream and free all system resources related to this stream. |
int available () |
Return The next method invoked on this input stream can be an estimate of the remaining bytes that are read (or skipped) from this input stream in a blocked manner. |
Common construction methods of subclass FileInputStream
Construction method |
Description |
FileInputStream (File file) |
Creates a FileInputStream object from a file object. |
FileInputStream (String name) |
Creates a FileInputStream object from the name file path. |
Sample code
package Com.etc.io;//1. Importing related classes Import Java.io.fileinputstream;import Java.io.filenotfoundexception;import java.io.IOException; public class Fistest {public static void main (string[] args) {FileInputStream FIS = null; try {//2. construct file input Stream object FIS = new FileInputStream ("E:\\mydoc.txt"); 3. Read text file data byte[] words = new byte[1024];//build array, read 1024 bytes at a time while (Fis.read () > 0) { Fis.read (words); }//4. Output string str = new string (words, "utf-8"); System.out.println (str); } catch (FileNotFoundException e) {e.printstacktrace (); } catch (IOException e) {e.printstacktrace (); } finally {//5. Close the input stream try {if (FIS! = null) {fis.close (); }} catch (IOException e) {e.printstacktrace (); } } }}
2 FileOutputStream Write text file
Common methods of OutputStream class
Method |
Description |
void write (int c) |
Writes the specified bytes to this file output stream. |
void Write (byte[] buf) |
Writes a b.length byte from the specified byte array to this file output stream. |
void Write (byte[] b,int off,int len) |
Writes Len bytes from offset off in the specified byte array to this file output stream. |
void Close () |
Closes this file output stream and frees all system resources related to this stream. |
Common construction methods of subclass FileOutputStream
Construction method |
Description |
FileOutputStream (File file) |
Creates a file output stream that writes data to the file that is represented by the specified Files object. |
FileOutputStream (String name) |
Creates an output file stream that writes data to a file with the specified name. |
FileOutputStream (String name, Boolean append) |
Creates a file output stream that writes data to the file that is represented by the specified Files object. If the second argument is true, the bytes are written to the end of the file, not to the beginning of the file. |
Attention:
1. The first two methods of construction overwrite the contents of the file when writing data to the file.
2. When you create an FileOutputStream instance, an empty file is created automatically if the corresponding file does not exist.
3. The streams created by FileInputStream and FileOutputStream belong to the node stream and manipulate the data source directly.
Sample code
Package com.etc.io;//1. Importing IO-related class import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;public class Fostest {public static void Main (string[] args) { FileOutputStream fos = null;< c2/>try { //2. Construct FileOutputStream object fos = new FileOutputStream ("E://fos.txt"); 3. Write the data to a text file String text = "Learn Java well, make Progress day by day!" "; byte[] Words = Text.getbytes (); Fos.write (words, 0, words.length); System.out.println ("Data written to file succeeded"); } catch (FileNotFoundException e) { e.printstacktrace (); } catch (IOException e) { e.printstacktrace (); c14/>} finally { //4. Close the file stream try { if (fos! = null) { fos.close (); } } catch (IOException e) { e.printstacktrace ();}}}}
3 on-Machine exercises: Copying text files
Requirements Description
The file "My introduction. txt" is located in the D-packing directory and requires that the contents of this file be copied to E:\myFile\myInfo.txt.
Analysis
Read the text file using the FileInputStream implementation.
To write data to a text file using the FileOutputStream implementation
Implementation ideas
1. Create the file "D:\ my introduction. txt" and enter your own content
2. Create the C:\myFile directory.
3. Create an input stream FileInputStream object that is responsible for reading d:\ my end. txt file.
4. Create an output stream FileOutputStream object, responsible for writing the contents of the file to C:\myFile\myInfo.txt.
5. Create the broker array words, storing the contents of each read.
6. Through the loop to achieve the file read and write.
7. Turn off the input stream, output stream
Character Stream mode read-write text file 1 bufferedreader read text file
Reading a text file related class using a character stream
Reader
FileReader (Node stream)
BufferedReader (processing Flow)
Common methods of Reader class
int read ()
int read (char[] c)
int read (char[] c,int off,int len)
void Close ()
Common construction methods of subclass BufferedReader
Public BufferedReader (Reader in) //in typically use Fliereader objects
Subclass BufferedReader-specific methods
Public String ReadLine ()//read a line of information
Garbled problem
Scenario One: Conversion of byte streams to character stream
Text saved to utf-8 format
FileInputStream fis=new FileInputStream ("E:\\mydoc.txt");//Use InputStreamReader and set encoding format InputStreamReader fr=new InputStreamReader (FIS, "UTF-8"); BufferedReader br=new BufferedReader (FR);
Scenario Two: Refactoring strings
Sample code
Package com.etc.io;//1. Importing IO-related class import Java.io.bufferedreader;import java.io.filereader;import java.io.IOException; public class Brtest {public static void main (string[] args) {FileReader FR = null; BufferedReader br = null; try {//2. Create a FileReader object FR = new FileReader ("E:\\mydoc.txt"); 3. Create a BufferedReader object br = new BufferedReader (FR); 4. Read a row of data String line = Br.readline (); while (line! = null) {String str = new String (Line.getbytes (), "UTF-8"); System.out.println (str); line = Br.readline (); }} catch (IOException e) {System.out.println ("file does not exist!"); } finally {try {//6. Close Stream if (br! = null) br.close (); if (fr! = null) fr.close (); } catch (IOException e) {e.printstacktrace (); } } }}
2 BufferedWriter Write text file
Write a text file related class using a character stream
Writer
FileWriter (Node stream)
BufferedWriter (processing Flow)
Common methods of writer class
void write (String str)
void Write (String str,int off,int len)
void Close ()
void Flush ()
Common construction methods of subclass BufferedWriter
BufferedReader (Writer out) //in typically use Fliewriter objects
Sample code
Package COM.ETC.IO;//1, the introduction of IO-related class import Java.io.bufferedwriter;import java.io.filewriter;import java.io.IOException; public class Bwtest {public static void main (string[] args) {FileWriter FW = null; BufferedWriter bw = NULL; try {//2. Create a FileWriter object FW = new FileWriter ("E:\\hi.txt"); 3. Create a BufferedWriter object bw = new BufferedWriter (FW); 4. Write Data bw.write ("Hello everyone!") "); Bw.write ("I'm learning Java IO. "); Bw.newline (); Bw.write ("Please give me a lot of advice!" "); Bw.newline (); Bw.flush ();//Flush Buffer System.out.println ("Write File information successfully! "); } catch (IOException e) {System.out.println ("file does not exist!"); } finally {//5. Close Stream try {if (bw! = NULL) {bw.close (); } if (fw! = null) fw.close (); } catch (IOException ex) {ex.printstacktrace (); } } }}
3 on-machine exercise: replacing template files
Requirements Description
1, the format template is saved in the text file Person.template, the content is as follows:
Hello!
My name is {name} and I am a student of {grade}.
My major is {speciality}.
2, where {name}, {grade}, {speciality} is required to replace the content, now requires the template format to save personal data to a text file, that is {name}, {grade}, {speciality} replaced with a specific individual.
Analysis
1. read files using Reader implementation class
2. Replace the content with the replace (Char OldChar, char Newchar) method of String
3, using writer to implement the class write file
BYTE stream read-write binary file 1 DataInputStream class reading binary (processing stream)
Subclass of FileInputStream
Using read binaries in conjunction with the FileInputStream class
2 DataOutputStream class Write binary file (process stream)
Subclass of FileOutputStream
Using write binaries in conjunction with the FileOutputStream class
3 Sample Code
/** * binary File copy * @param sFile source file * @param dfile target file */public static void Copybinfile (file sFile, file Dfile) {FileInputStream FIS = null;//define byte stream input node flow datainputstream dis = null;//define binary input processing stream FILEOUTP Utstream fos = null;//definition byte stream output node flow dataoutputstream dos = null;//define binary output processing flow try {fis = new File InputStream (SFile); dis = new DataInputStream (FIS);//build binary input processing stream fos = new FileOutputStream (dfile); DOS = new DataOutputStream (FOS);//build binary output processing stream int temp; while (temp = Dis.read ())! =-1) {//Read data dos.write (temp);//write Data} System.out.print ln ("Copy file" + sfile.getname () + "Success! "); System.out.println ("File path:" + Sfile.getabsolutepath ()); } catch (FileNotFoundException e) {e.printstacktrace (); } catch (IOException e) {e.printstacktrace (); } finally {//close resource try { if (dos = null) {dos.close (); } if (fos! = null) {fos.close (); } if (dis! = null) {dis.close (); } if (FIS! = null) {fis.close (); }} catch (IOException e) {e.printstacktrace (); } } }
4 on-machine exercise: Copy an image file from the D disk to the E-drive
JavaSE-19 IO