1. Use of File Class
- java.io.File class: abstract representation of file and file directory paths, platform independent
- File can create, delete, and rename files and directories, but File cannot access the file content itself.
- If you need to access the file content itself, you need to use input/output streams.
- To represent a real file or directory in a Java program, you must have a File object, but a File object in a Java program may not have a real file or directory.
- File objects can be passed as constructors to streams as parameters
Common Constructors
1.public File(String pathname)
Create a File object with pathname as the path, either absolute or relative, if
pathname is a relative path, then the default current path is stored in the system property user.dir.
Absolute path: A fixed path, starting with a drive letter
Relative Path: Start relative to a location
2. public File(String parent,String child)
File objects are created with parent as parent path and child as child path.
3. public File(File parent,String child)
Create File objects from a parent File object and a subfile path
path separator
- Each level of directory in the path is separated by a path separator.
- Path separators are system dependent: windows and DOS systems use'\'by default to represent UNIX and URL s using'/'
- Java programs support cross-platform running, so use path separators with caution.
- To address this potential, the File class provides a constant: public static final String separator.Depending on the operating system, delimiters are dynamically provided.
common method
_File class acquisition function
_public String getAbsolutePath(): Get absolute path
_public String getPath(): Get Path
public String getName(): Get Name
public String getParent(): Get the path to the upper file directory.If not, return null
public long length(): Gets the length of the file (that is, the number of bytes).Cannot get the length of the directory.
_public long lastModified(): Gets the last modification time, in milliseconds
public String[] list(): Gets an array of names of all files or file directories in the specified directory
_public File[] listFiles(): Gets an array of Files for all files or file directories in the specified directory
Rename function of File class
public boolean renameTo(File dest): Rename the file to the specified file path
Judgement Function of File Class
_public boolean isDirectory(): Determine if it is a file directory
_public boolean isFile(): Determine if it is a file
_public boolean exists(): Determine existence
_public boolean canRead(): Determine whether it is readable
_public boolean canWrite(): Determine Writability
_public boolean isHidden(): Determine whether to hide
File Class Creation Function
public boolean createNewFile(): Create a file.If the file exists, it is not created and false is returned
public boolean mkdir(): Create a file directory.If this file directory exists, it will not be created.
If the upper directory of this file directory does not exist, it will not be created.
public boolean mkdirs(): Create a file directory.If the upper file directory does not exist, create it together
Important: If you create a file or if the file directory does not have a drive letter path, the default is in the project
Under the path.
Delete function of File class
public boolean delete(): Delete a file or folder
Remove precautions:
Deletes in Java do not go to the Recycle Bin.
To delete a file directory, note that it cannot contain files or file directories
Code demonstration
/** * File Use of classes * * 1. File An object of a class that represents a file or a file directory (commonly known as a folder) * 2. File Class declaration under java.io package * 3. File Class involves the creation, deletion, renaming, modification time, file size, etc. of a file or file directory. * Writing or reading the contents of the file is not involved.If you need to read or write the contents of a file, you must use an IO stream to do so. * 4. Subsequent File class objects are often passed as parameters to the constructor of the stream, indicating the "end point" to read or write to. * * * * * @author shkstart * @create 2019 4:05 p.m. */ public class FileTest { /* 1.How to create an instance of a File class File(String filePath) File(String parentPath,String childPath) File(File parentFile,String childPath) 2. Relative path: A path specified in comparison to a path. Absolute path: The path to a file or directory containing drive letters 3.path separator windows:\\ unix:/ */ @Test public void test1(){ //Constructor 1 File file1 = new File("hello.txt");//Relative to current module File file2 = new File("D:\\workspace_idea1\\JavaSenior\\day08\\he.txt"); System.out.println(file1); System.out.println(file2); //Constructor 2: File file3 = new File("D:\\workspace_idea1","JavaSenior"); System.out.println(file3); //Constructor 3: File file4 = new File(file3,"hi.txt"); System.out.println(file4); } /* public String getAbsolutePath(): Get absolute path public String getPath() : Get Path public String getName() : Get Name public String getParent(): Gets the upper file directory path.If not, return null public long length() : Gets the length of the file (that is, the number of bytes).Cannot get the length of the directory. public long lastModified() : Gets the last modification time, in milliseconds The following two methods apply to file directories: public String[] list() : Gets an array of names of all files or file directories in the specified directory public File[] listFiles() : Gets an array of Files for all files or File directories in the specified directory */ @Test public void test2(){ File file1 = new File("hello.txt"); File file2 = new File("d:\\io\\hi.txt"); System.out.println(file1.getAbsolutePath()); System.out.println(file1.getPath()); System.out.println(file1.getName()); System.out.println(file1.getParent()); System.out.println(file1.length()); System.out.println(new Date(file1.lastModified())); System.out.println(); System.out.println(file2.getAbsolutePath()); System.out.println(file2.getPath()); System.out.println(file2.getName()); System.out.println(file2.getParent()); System.out.println(file2.length()); System.out.println(file2.lastModified()); } @Test public void test3(){ File file = new File("D:\\workspace_idea1\\JavaSenior"); String[] list = file.list(); for(String s : list){ System.out.println(s); } System.out.println(); File[] files = file.listFiles(); for(File f : files){ System.out.println(f); } } /* public boolean renameTo(File dest):Rename the file to the specified file path For example: file1.renameTo(file2): To ensure true returns, file1 needs to be present on the hard disk, and file2 cannot be present on the hard disk. */ @Test public void test4(){ File file1 = new File("hello.txt"); File file2 = new File("D:\\io\\hi.txt"); boolean renameTo = file2.renameTo(file1); System.out.println(renameTo); } /* public boolean isDirectory(): Determine if it is a file directory public boolean isFile() : Determine whether it is a file public boolean exists() : Judging whether there is public boolean canRead() : Determine Readability public boolean canWrite() : Determine Writability public boolean isHidden() : Determine whether to hide */ @Test public void test5(){ File file1 = new File("hello.txt"); file1 = new File("hello1.txt"); System.out.println(file1.isDirectory()); System.out.println(file1.isFile()); System.out.println(file1.exists()); System.out.println(file1.canRead()); System.out.println(file1.canWrite()); System.out.println(file1.isHidden()); System.out.println(); File file2 = new File("d:\\io"); file2 = new File("d:\\io1"); System.out.println(file2.isDirectory()); System.out.println(file2.isFile()); System.out.println(file2.exists()); System.out.println(file2.canRead()); System.out.println(file2.canWrite()); System.out.println(file2.isHidden()); } /* Create the corresponding file or file directory on the hard disk public boolean createNewFile() : Create a file.If the file exists, it is not created and false is returned public boolean mkdir() : Create a file directory.If this file directory exists, it will not be created.If the upper directory of this file directory does not exist, it will not be created. public boolean mkdirs() : Create a file directory.If this file directory exists, it will not be created.If the upper file directory does not exist, create it together Delete files or file directories from disk public boolean delete(): Delete files or folders Delete note: Delete in Java does not go to the Recycle Bin. */ @Test public void test6() throws IOException { File file1 = new File("hi.txt"); if(!file1.exists()){ //File Creation file1.createNewFile(); System.out.println("Created successfully"); }else{//File Exists file1.delete(); System.out.println("Delete succeeded"); } } @Test public void test7(){ //Creation of File Directory File file1 = new File("d:\\io\\io1\\io3"); boolean mkdir = file1.mkdir(); if(mkdir){ System.out.println("Create Success 1"); } File file2 = new File("d:\\io\\io1\\io4"); boolean mkdir1 = file2.mkdirs(); if(mkdir1){ System.out.println("Create Success 2"); } //To delete successfully, there must be no subdirectories or files in the io4 file directory File file3 = new File("D:\\io\\io1\\io4"); file3 = new File("D:\\io\\io1"); System.out.println(file3.delete()); } }
Java IO principles
1. I/O is the abbreviation of Input/Output. I/O technology is a very practical technology for
Processing data transfer between devices.Such as reading/writing files, network communication, etc.
2. In Java programs, input/output operations to data are streamed
Method.
3. Various "stream" classes and interfaces are provided under the java.io package to get different kinds of
Data, and input or output data through standard methods.
input: Reads external data (data from storage devices such as disks, discs) into programs (memory).
Output output: Output program (memory) data to disk, disc, and other storage devices.
FileInputOutputStreamTest
package com.atguigu.java; import org.junit.Test; import java.io.*; /** * Test the use of FileInputStream and FileOutputStream * * Conclusion: * 1. For text files (.txt,.java,.c,.cpp), use character stream processing * 2. For non-text files (.jpg,.mp3,.mp4,.avi,.doc,.ppt,...), use byte stream processing * * * * @author shkstart * @create 2019 2:13 p.m. */ public class FileInputOutputStreamTest { //Text files can be processed using the byte stream FileInputStream, which can cause garbage. @Test public void testFileInputStream() { FileInputStream fis = null; try { //1. Documentation File file = new File("hello.txt"); //2. Flow generation fis = new FileInputStream(file); //3. Read data byte[] buffer = new byte[5]; int len;//Record the number of bytes read at a time while((len = fis.read(buffer)) != -1){ String str = new String(buffer,0,len); System.out.print(str); } } catch (IOException e) { e.printStackTrace(); } finally { if(fis != null){ //4. Close resources try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } /* Implement copying of pictures */ @Test public void testFileInputOutputStream() { FileInputStream fis = null; FileOutputStream fos = null; try { // File srcFile = new File("Love and Friendship.jpg"); File destFile = new File("Love and Friendship 2.jpg"); // fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); //The process of replication byte[] buffer = new byte[5]; int len; while((len = fis.read(buffer)) != -1){ fos.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { if(fos != null){ // try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if(fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } //Copy of files under specified path public void copyFile(String srcPath,String destPath){ FileInputStream fis = null; FileOutputStream fos = null; try { // File srcFile = new File(srcPath); File destFile = new File(destPath); // fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); //The process of replication byte[] buffer = new byte[1024]; int len; while((len = fis.read(buffer)) != -1){ fos.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { if(fos != null){ // try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if(fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void testCopyFile(){ long start = System.currentTimeMillis(); String srcPath = "C:\\Users\\Administrator\\Desktop\\01-video.avi"; String destPath = "C:\\Users\\Administrator\\Desktop\\02-video.avi"; // String srcPath = "hello.txt"; // String destPath = "hello3.txt"; copyFile(srcPath,destPath); long end = System.currentTimeMillis(); System.out.println("The replication operation takes time:" + (end - start));//618 } }
FileReaderWriterTest
package com.atguigu.java; import org.junit.Test; import java.io.*; /** * * 1. Classification of flow: * 1.Operational Data Units: Byte Stream, Character Stream * 2.Flow direction of data: input flow, output flow * 3.Role of flow: node flow, process flow * * 2. Architecture of Stream * Abstract base class node stream (or file stream) buffer stream (one that handles streams) * InputStream FileInputStream (read(byte[] buffer)) BufferedInputStream (read(byte[] buffer)) * OutputStream FileOutputStream (write(byte[] buffer,0,len) BufferedOutputStream (write(byte[] buffer,0,len) / flush() * Reader FileReader (read(char[] cbuf)) BufferedReader (read(char[] cbuf) / readLine()) * Writer FileWriter (write(char[] cbuf,0,len) BufferedWriter (write(char[] cbuf,0,len) / flush() * * * * @author shkstart * @create 2019 10:40 a.m. */ public class FileReaderWriterTest { public static void main(String[] args) { File file = new File("hello.txt");//Compare to current project System.out.println(file.getAbsolutePath()); File file1 = new File("day09\\hello.txt"); System.out.println(file1.getAbsolutePath()); } /* Read the contents of the hello.txt file under day09 into the program and output to the console Description points: 1. read()Understanding: Returns a character read in.Return-1 if the end of the file is reached 2. Handling exceptions: In order to ensure that the stream resources can be closed.Require try-catch-finally processing 3. The read file must exist, otherwise it will be reported to FileNotFoundException. */ @Test public void testFileReader(){ FileReader fr = null; try { //1. Instantiate an object of the File class, specifying the file to be manipulated File file = new File("hello.txt");//Compare to current Module //2. Provide specific streams fr = new FileReader(file); //3. Read in data //read(): Returns a character read in.Return-1 if the end of the file is reached //Mode 1: // int data = fr.read(); // while(data != -1){ // System.out.print((char)data); // data = fr.read(); // } //Mode 2: Grammatical modifications to Mode 1 int data; while((data = fr.read()) != -1){ System.out.print((char)data); } } catch (IOException e) { e.printStackTrace(); } finally { //4. Closing of streams // try { // if(fr != null) // fr.close(); // } catch (IOException e) { // e.printStackTrace(); // } //or if(fr != null){ try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } } //Upgrade for read(): overload method using read @Test public void testFileReader1() { FileReader fr = null; try { //1. Instantiation of File class File file = new File("hello.txt"); //2. Instantiation of FileReader stream fr = new FileReader(file); //3. Read-in operation //read(char[] cbuf): Returns the number of characters read into the cbuf array each time.Return-1 if the end of the file is reached char[] cbuf = new char[5]; int len; while((len = fr.read(cbuf)) != -1){ //Mode 1: //Wrong Writing // for(int i = 0;i < cbuf.length;i++){ // System.out.print(cbuf[i]); // } //Correct Writing // for(int i = 0;i < len;i++){ // System.out.print(cbuf[i]); // } //Mode 2: //Wrong Writing, Writing for Wrong One // String str = new String(cbuf); // System.out.print(str); //Correct Writing String str = new String(cbuf,0,len); System.out.print(str); } } catch (IOException e) { e.printStackTrace(); } finally { if(fr != null){ //4. Closing of resources try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } } /* Write data from memory into a file on your hard disk. Explain: 1. Output operation, the corresponding File may not exist.No exceptions will be reported 2. File If the file in the corresponding hard disk does not exist, it will be created automatically during the output process. File If a file exists on the corresponding hard disk: If the constructor used by the stream is: FileWriter(file,false) / FileWriter(file): Overwrite the original file If the constructor used by the stream is: FileWriter(file,true): does not overwrite the original file, but appends content to it */ @Test public void testFileWriter() { FileWriter fw = null; try { //1. Provide an object of the File class indicating the file to which it is written File file = new File("hello1.txt"); //2. Provide an object for FileWriter to write out data fw = new FileWriter(file,false); //3. Write Out Operations fw.write("I have a dream!\n"); fw.write("you need to have a dream!"); } catch (IOException e) { e.printStackTrace(); } finally { //4. Closing of Stream Resources if(fw != null){ try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void testFileReaderFileWriter() { FileReader fr = null; FileWriter fw = null; try { //1. Create an object of the File class that specifies the files read in and written out File srcFile = new File("hello.txt"); File destFile = new File("hello2.txt"); //You cannot use character streams to process byte data such as pictures // File srcFile = new File("love and friendship.jpg"); // File destFile = new File("love and friendship 1.jpg"); //2. Create objects for input and output streams fr = new FileReader(srcFile); fw = new FileWriter(destFile); //3. Read-in and write-out of data char[] cbuf = new char[5]; int len;//Record the number of characters read into the cbuf array each time while((len = fr.read(cbuf)) != -1){ //Write len characters at a time fw.write(cbuf,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { //4. Close Stream Resources //Mode 1: // try { // if(fw != null) // fw.close(); // } catch (IOException e) { // e.printStackTrace(); // }finally{ // try { // if(fr != null) // fr.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } //Mode 2: try { if(fw != null) fw.close(); } catch (IOException e) { e.printStackTrace(); } try { if(fr != null) fr.close(); } catch (IOException e) { e.printStackTrace(); } } } }
BufferedTest
package com.atguigu.java; import org.junit.Test; import java.io.*; /** * One of the processing streams: the use of buffer streams * * 1.Buffer Stream: * BufferedInputStream * BufferedOutputStream * BufferedReader * BufferedWriter * * 2.Role: Provides read and write speeds for streams * Reason for increased read and write speed: A buffer is provided internally * * 3. Processing streams means "socketing" on the basis of existing streams. * * @author shkstart * @create 2019 2:44 p.m. */ public class BufferedTest { /* Implement copying of non-text files */ @Test public void BufferedStreamTest() throws FileNotFoundException { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { //1. Documentation File srcFile = new File("Love and Friendship.jpg"); File destFile = new File("Love and Friendship 3.jpg"); //2. Flow generation //2.1 Node Flow FileInputStream fis = new FileInputStream((srcFile)); FileOutputStream fos = new FileOutputStream(destFile); //2.2 Buffer Flow bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); //3. Details of copying: read, write byte[] buffer = new byte[10]; int len; while((len = bis.read(buffer)) != -1){ bos.write(buffer,0,len); // bos.flush();//Refresh Buffer } } catch (IOException e) { e.printStackTrace(); } finally { //4. Resource shutdown //Requirements: Close the outer flow before closing the inner flow if(bos != null){ try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if(bis != null){ try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } //Description: When the outer layer flow is closed, the inner layer flow is also automatically closed.We can omit the closure of the inner layer. // fos.close(); // fis.close(); } } //Method of Implementing File Copy public void copyFileWithBuffered(String srcPath,String destPath){ BufferedInputStream bis = null; BufferedOutputStream bos = null; try { //1. Documentation File srcFile = new File(srcPath); File destFile = new File(destPath); //2. Flow generation //2.1 Node Flow FileInputStream fis = new FileInputStream((srcFile)); FileOutputStream fos = new FileOutputStream(destFile); //2.2 Buffer Flow bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); //3. Details of copying: read, write byte[] buffer = new byte[1024]; int len; while((len = bis.read(buffer)) != -1){ bos.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { //4. Resource shutdown //Requirements: Close the outer flow before closing the inner flow if(bos != null){ try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if(bis != null){ try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } //Description: When the outer layer flow is closed, the inner layer flow is also automatically closed.We can omit the closure of the inner layer. // fos.close(); // fis.close(); } } @Test public void testCopyFileWithBuffered(){ long start = System.currentTimeMillis(); String srcPath = "C:\\Users\\Administrator\\Desktop\\01-video.avi"; String destPath = "C:\\Users\\Administrator\\Desktop\\03-video.avi"; copyFileWithBuffered(srcPath,destPath); long end = System.currentTimeMillis(); System.out.println("The replication operation takes time:" + (end - start));//618 - 176 } /* Using BufferedReader and BufferedWriter to copy text files */ @Test public void testBufferedReaderBufferedWriter(){ BufferedReader br = null; BufferedWriter bw = null; try { //Create files and corresponding streams br = new BufferedReader(new FileReader(new File("dbcp.txt"))); bw = new BufferedWriter(new FileWriter(new File("dbcp1.txt"))); //Read and write operations //Mode 1: Use a char[] array // char[] cbuf = new char[1024]; // int len; // while((len = br.read(cbuf)) != -1){ // bw.write(cbuf,0,len); // // bw.flush(); // } //Mode 2: Use String String data; while((data = br.readLine()) != null){ //Method 1: // Bw.write (data +'\n'); //data does not contain line breaks //Method 2: bw.write(data);//data does not contain line breaks bw.newLine();//Provide Line Break Operations } } catch (IOException e) { e.printStackTrace(); } finally { //close resource if(bw != null){ try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } if(br != null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
InputStreamReaderTest
package com.atguigu.java; import org.junit.Test; import java.io.*; /** * Processing Stream Two: Use of Converted Stream * 1.Conversion stream: belongs to character stream * InputStreamReader: Converts a byte input stream to a character input stream * OutputStreamWriter: Converts the output stream of a character to the output stream of a byte * * 2.Role: Provides conversion between byte stream and character stream * * 3. Decode: Byte, Byte Array - > Character Array, String * Encoding: Character Array, String--->Byte, Byte Array * * * 4.character set *ASCII: US Standard Information Exchange Code. Represented in 7 bits of a byte. ISO8859-1: Latin code table.European code table Represents in 8 bits of a byte. GB2312: Chinese Coding Table for China.Encode all characters up to two bytes GBK: China's Chinese coding table has been upgraded to incorporate more Chinese characters.Up to two byte encoding Unicode: International Code, which combines all the characters currently used by humans.Assign a unique character code to each character.All text is represented by two bytes. UTF-8: A variable-length encoding in which one character can be represented by 1-4 bytes. * * * @author shkstart * @create 2019 4:25 p.m. */ public class InputStreamReaderTest { /* To handle exceptions at this point, try-catch-finally should still be used InputStreamReader Use to convert byte input stream to character input stream */ @Test public void test1() throws IOException { FileInputStream fis = new FileInputStream("dbcp.txt"); // InputStreamReader isr = new InputStreamReader(fis); //Use the system default character set //Parameter 2 specifies the character set, depending on which character set is used when the file dbcp.txt is saved InputStreamReader isr = new InputStreamReader(fis,"UTF-8");//Use the system default character set char[] cbuf = new char[20]; int len; while((len = isr.read(cbuf)) != -1){ String str = new String(cbuf,0,len); System.out.print(str); } isr.close(); } /* To handle exceptions at this point, try-catch-finally should still be used Combining InputStreamReader with OutputStreamWriter */ @Test public void test2() throws Exception { //1. Documentation and streaming File file1 = new File("dbcp.txt"); File file2 = new File("dbcp_gbk.txt"); FileInputStream fis = new FileInputStream(file1); FileOutputStream fos = new FileOutputStream(file2); InputStreamReader isr = new InputStreamReader(fis,"utf-8"); OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk"); //2. Read and write process char[] cbuf = new char[20]; int len; while((len = isr.read(cbuf)) != -1){ osw.write(cbuf,0,len); } //3. Close resources isr.close(); osw.close(); } }
OtherStreamTest
package com.atguigu.java; import org.junit.Test; import java.io.*; /** * Use of other streams * 1.Standard input and output streams * 2.Print Stream * 3.data stream * * @author shkstart * @create 2019 6:11 p.m. */ public class OtherStreamTest { /* 1.Standard input and output streams 1.1 System.in:Standard input stream, entered from keyboard by default System.out:Standard output stream, output from console by default 1.2 System Class setIn(InputStream is) / setOut(PrintStream ps) way to re-specify the flow of input and output. 1.3 Practice: Entering a string from the keyboard requires that the entire line of string read be converted to uppercase output.Then continue with the input operation. Until you enter "e" or "exit", exit the program. Method one: Using Scanner implementation, call next() to return a string Method 2: Implement using System.in.System.in --->Conversion Stream ---> ReadLine of BufferedReader () */ public static void main(String[] args) { BufferedReader br = null; try { InputStreamReader isr = new InputStreamReader(System.in); br = new BufferedReader(isr); while (true) { System.out.println("Please enter a string:"); String data = br.readLine(); if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)) { System.out.println("Program End"); break; } String upperCase = data.toUpperCase(); System.out.println(upperCase); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } /* 2. Print Stream and PrinttWriter 2.1 Provides a series of overloaded prints () and printlns () 2.2 Practice: */ @Test public void test2() { PrintStream ps = null; try { FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\text.txt")); // Create a print output stream, set to automatic refresh mode (output buffers are refreshed when line breaks or bytes'\n'are written) ps = new PrintStream(fos, true); if (ps != null) {// Change Standard Output Stream (Console Output) to File System.setOut(ps); } for (int i = 0; i <= 255; i++) { // Output ASCII Characters System.out.print((char) i); if (i % 50 == 0) { // Every 50 rows of data System.out.println(); // Line Break } } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (ps != null) { ps.close(); } } } /* 3. data stream 3.1 DataInputStream And DataOutputStream 3.2 Role: Variables or strings used to read or write out basic data types Exercise: Write out the strings in memory, variables of basic data types to a file. Note: try-catch-finally should still be used when handling exceptions. */ @Test public void test3() throws IOException { //1. DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt")); //2. dos.writeUTF("Liu Jianchen"); dos.flush();//Refresh operation to write in-memory data to a file dos.writeInt(23); dos.flush(); dos.writeBoolean(true); dos.flush(); //3. dos.close(); } /* Reads basic data type variables and strings stored in files into memory and saves them in variables. Note: Read different types of data in the same order as the data you saved when you first wrote the file! */ @Test public void test4() throws IOException { //1. DataInputStream dis = new DataInputStream(new FileInputStream("data.txt")); //2. String name = dis.readUTF(); int age = dis.readInt(); boolean isMale = dis.readBoolean(); System.out.println("name = " + name); System.out.println("age = " + age); System.out.println("isMale = " + isMale); //3. dis.close(); } }
Exercise: Get the number of occurrences of characters in the text and write the data to a file
package com.atguigu.exer; import org.junit.Test; import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Exercise 3: Get the number of occurrences of characters in the text and write the data to a file * * Ideas: * 1.Traverse through each character of the text * 2.The number of occurrences of a character exists in the Map * * Map<Character,Integer> map = new HashMap<Character,Integer>(); * map.put('a',18); * map.put('You', 2); * * 3.Write data from map to file * * @author shkstart * @create 2019 3:47 p.m. */ public class WordCount { /* Description: If unit testing is used, the file relative path is the current module If you use the main() test, the file relative path is the current project */ @Test public void testWordCount() { FileReader fr = null; BufferedWriter bw = null; try { //1. Create a Map Collection Map<Character, Integer> map = new HashMap<Character, Integer>(); //2. Traverse through each character and place the number of occurrences of each character in the map fr = new FileReader("dbcp.txt"); int c = 0; while ((c = fr.read()) != -1) { //int Restore char char ch = (char) c; // Determine if char first appears in map if (map.get(ch) == null) { map.put(ch, 1); } else { map.put(ch, map.get(ch) + 1); } } //3. Exist data in map in file count.txt //3.1 Create Writer bw = new BufferedWriter(new FileWriter("wordcount.txt")); //3.2 Traverse the map and write data Set<Map.Entry<Character, Integer>> entrySet = map.entrySet(); for (Map.Entry<Character, Integer> entry : entrySet) { switch (entry.getKey()) { case ' ': bw.write("Spaces=" + entry.getValue()); break; case '\t'://\t denotes the tab key character bw.write("tab key=" + entry.getValue()); break; case '\r':// bw.write("Enter=" + entry.getValue()); break; case '\n':// bw.write("Line Break=" + entry.getValue()); break; default: bw.write(entry.getKey() + "=" + entry.getValue()); break; } bw.newLine(); } } catch (IOException e) { e.printStackTrace(); } finally { //4. Shutdown if (fr != null) { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } if (bw != null) { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
package com.atguigu.java; import org.junit.Test; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; /** * RandomAccessFile Use * 1.RandomAccessFile Direct inheritance from the java.lang.Object class implements the DataInput and DataOutput interfaces * 2.RandomAccessFile It can be used as both an input stream and an output stream * * 3.If RandomAccessFile is the output stream, the written file is automatically created during execution if it does not exist. * If the written out file exists, the contents of the original file will be overwritten.(By default, override from scratch) * * 4. RandomAccessFile "inserts" data through related operations * * @author shkstart * @create 2019 11:18 a.m. */ public class RandomAccessFileTest { @Test public void test1() { RandomAccessFile raf1 = null; RandomAccessFile raf2 = null; try { //1. raf1 = new RandomAccessFile(new File("Love and Friendship.jpg"),"r"); raf2 = new RandomAccessFile(new File("Love and Friendship 1.jpg"),"rw"); //2. byte[] buffer = new byte[1024]; int len; while((len = raf1.read(buffer)) != -1){ raf2.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { //3. if(raf1 != null){ try { raf1.close(); } catch (IOException e) { e.printStackTrace(); } } if(raf2 != null){ try { raf2.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void test2() throws IOException { RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw"); raf1.seek(3);//Set the pointer to the position marked 3 at the corner raf1.write("xyz".getBytes());// raf1.close(); } /* Use RandomAccessFile to insert data */ @Test public void test3() throws IOException { RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw"); raf1.seek(3);//Set the pointer to the position marked 3 at the corner //Save all data after pointer 3 into StringBuilder StringBuilder builder = new StringBuilder((int) new File("hello.txt").length()); byte[] buffer = new byte[20]; int len; while((len = raf1.read(buffer)) != -1){ builder.append(new String(buffer,0,len)) ; } //Call back the pointer and write "xyz" raf1.seek(3); raf1.write("xyz".getBytes()); //Write data from StringBuilder to a file raf1.write(builder.toString().getBytes()); raf1.close(); //Think: Replace StringBuilder with ByteArrayOutputStream } }