How to distinguish input stream from output stream in I/O stream operation?
I/O flow is relative to computer memory,
Input stream is to input the contents of the file into memory and display it later, so the input stream can be used to read data.
Output stream means that data is output from memory to a file to add content to a file, so the output stream can be used to add the content of the file.
Basic byte stream: read one byte at a time / read one byte array at a time
Byte buffer stream: read one byte at a time / read one byte array at a time
Character conversion stream: InputStreamReader(InputStream in)
OutputStreamWriter(OutputStream out)
Read one character at a time / read one character array at a time
Convenient class of conversion flow
FileReader(String name)
FileWriter(String writer)
Read one character at a time / read one character array at a time
BufferedReader/BufferedWriter
Read one character at a time / read one character array at a time
The unique function reads one line at a time
Member method:
Create / delete / duplicate name
public boolean createNewFile() throws IOException: indicates to create a file: if it does not exist, it will be created
public boolean mkdir(): create a folder. If it does not exist, create it; Otherwise, false is returned
public boolean mkdirs(): create multiple files. If the parent directory does not exist, it will be created
public boolean delete(): delete files or folders (if you delete a folder, the folder must be an empty directory)
public boolean renameTo(File dest): Rename
Judgment function:
Is public boolean canRead() readable
Is public boolean canWrite() writable
public boolean exists(): does it exist
public boolean isFile(): is it a file
public boolean isDirectory(): is it a folder
public boolean isHidden(): hide
public class FileDemo2 { public static void main(String[] args) { //Create a File object to describe the AAA under the current project Txt File File file = new File("aaa.txt") ; System.out.println(file.canRead()); System.out.println(file.canWrite()); System.out.println(file.exists()); System.out.println(file.isDirectory());//false System.out.println(file.isFile()); System.out.println(file.isHidden()); System.out.println(file.length()); System.out.println(file.getName());
Advanced access features:
public long length()
public String getName(): get the name of the file or directory represented by the abstract path name
public File[] listFiles(): get the File array of all files and folders in a directory
public String[] list(): get the string array of files and directories represented by an abstract pathname
Requirements:
Get the names of all folders and files under disk D
public class FileDemo2 { public static void main(String[] args) { // public File[] listFiles(): get the File array of all files and folders in a directory //Description disk D File file2 = new File("d://") ; File[] fileArray = file2.listFiles(); //Prevent null pointer exceptions if(fileArray!=null){ for(File f :fileArray){ System.out.println(f.getName()); } } System.out.println("----------------------------------"); //public String[] list(): get the string array of files and directories represented by an abstract pathname String[] strArray = file2.list(); if(strArray!=null){ for(String s:strArray){ System.out.println(s); } }
Requirements:
1. Obtain all data under disk D jpg ending file
Analysis:
(1) describe the lower D disk
(2)public File[] listFiles(): get the File array of all files and folders in disk D
(3) make a non judgment on the obtained array. If it is not null, judge again
(4) judge whether the File is a File
(5) judgment: the document must be in jpg end; String class endsWith(".jpg")
public class FileTest { public static void main(String[] args) { //1) Description disk D File file = new File("D://") ; //2) Get the File array of all files and folders under the drive letter File[] fileArray = file.listFiles();//This step did not directly obtain the desired information jpg file //Some later judgments if(fileArray!=null){ for(File f:fileArray){ //Judge whether f is a file if(f.isFile()){ //It's a file //Judge whether its name is in jpg end if(f.getName().endsWith(".jpg")){ System.out.println(f.getName()); } } } } } }
2. Use filter [file name filter: interface]
Member method:
boolean accept(File dir,String name): test whether the specified file is included in the file list. If true, add the file to the file list
(1) Describe the lower D disk
(2) public File[] listFiles(FilenameFilter filenamefilter):
When you get the File array under disk D, you have specified the File to filter
public class FileTest { public static void main(String[] args) { File srcFile = new File("D://") ; //Get the File array of all files and folders under the current D disk, and filter the File names //public File[] listFiles(FilenameFilter filter) File[] files = srcFile.listFiles(new FilenameFilter() {//Anonymous inner class of interface @Override public boolean accept(File dir, String name) { //Return true: indicates that the specified file is added to the list file //Describes the abstract path represented by the File File file = new File(dir, name); //Two conditions: file is a file and the file name of file ends with ". jpg" return file.isFile() && file.getName().endsWith(".jpg"); } }); if(files!=null){ for(File f :files){ System.out.println(f.getName()); } } } }
II Method recursion: a phenomenon in which a method calls the method itself (not a method nested method)
prerequisite
(1) There must be a member method
(2) There must be an exit condition (end condition) for method recursion. If there is no exit condition, it is dead recursion
(3) There are still certain laws
Note: there is no recursion in the construction method
Requirements:
Use the recursive method to delete many directories in a demo folder on disk D. There may be directories in each directory. Delete the tape in all these directories java file
analysis:
(1) Describe the demo folder on disk D. srcfile = new file ("D: / / demo")
(2) Call recursive delete method
Recursively delete java files in multi-level directories
public void deleteSrcFile(File srcFile){
Get all folders of srcFile and the File array of files
Non null judgment
Judge if it is a folder
Go back to 2) continue calling recursive deletion
Otherwise, it is a file
Judge whether to use java file
Finally delete the file}
public class DiGuiTest { public static void main(String[] args) { //Describes the demo folder of disk D File srcFloder = new File("d://demo") ; //Call the method of recursive deletion deleteFloder(srcFloder) ; } public static void deleteFloder(File srcFloder) { //Get all the files under srcFloder and the File array of files File[] fileArray = srcFloder.listFiles(); if(fileArray!=null){ for(File file:fileArray){ //Get each file object //If file is a folder, continue back to deletefolder (srcfloder); remove folders if(file.isDirectory()){ deleteFloder(file) ; }else{ //Judgment is a document and must be based on java end file if(file.getName().endsWith(".java")){ //While deleting -- get the name System.out.println(file.getName()+"------------"+file.delete()); } } } //remove folders System.out.println(srcFloder.getName()+"----"+srcFloder.delete()); } } }
III
1. File data read (FileInputStream) ---- > read the contents of the file into the memory (one byte read)
public class test1 { public static void main(String[] args) { FileInputStream fis = null; try { fis = new FileInputStream("F:\\Ideaproject\\Day28\\src\\lhb.txt"); int by = 0; while ((by=fis.read()) != -1){ System.out.print((char)by); } } catch (IOException e) { e.printStackTrace(); }finally { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
2. File data reading (FileInputStream) ---- > read the contents of the file into memory (byte array reading)
public class test1 { public static void main(String[] args) { FileInputStream fis = null; try { fis = new FileInputStream("F:\\Ideaproject\\Day28\\src\\lhb.txt"); byte[] bytes = new byte[1024]; int len = 0; while ((len=fis.read(bytes))!= -1){ System.out.println(new String(bytes,0,len)); } } catch (IOException e) { e.printStackTrace(); }finally { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
IV Characteristics of buffer stream: provide buffer capitalization: 8 times 1024} or increase the reading speed through the underlying stream (FileInputStream)
Bufferedinputstream
Construction method
BufferedInputStream(InputStream in): default buffer uppercase (large enough)
Provide a specified buffer size
BufferedInputStream(InputStream in, int size)
(1) One byte one byte read
public class test1 { public static void main(String[] args) throws FileNotFoundException { BufferedInputStream bis = null; try { bis = new BufferedInputStream(new FileInputStream("F:\\Ideaproject\\Day28\\src\\lhb.txt")); //Byte read int by = 0; while ((by = bis.read())!=-1){ System.out.print((char) by); } } catch (IOException e) { e.printStackTrace(); }finally { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
(2) Byte array read
public class test1 { public static void main(String[] args) throws FileNotFoundException { BufferedInputStream bis = null; try { bis = new BufferedInputStream(new FileInputStream("F:\\Ideaproject\\Day28\\src\\lhb.txt")); //Byte array read byte[] bytes = new byte[1024]; int len = 0; while ((len = bis.read(bytes))!=-1){ System.out.print(new String(bytes,0,len)); } } catch (IOException e) { e.printStackTrace(); }finally { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Bufferedoutputstream
BufferedOutputStream(OutputStream out)
Recommended: the default buffer size is large enough to be 8 KB
Creates a new buffered output stream to write data to the specified underlying output stream.
BufferedOutputStream(OutputStream out, int size)
public class test1 { public static void main(String[] args) throws IOException { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("xaiona.txt")); bos.write("I love you!".getBytes()); bos.close(); } }
V
FileInputStream,FileOutputStream
The basic byte stream reads a byte array one at a time - a total of 116 milliseconds
The basic byte stream reads one byte at a time - a total of 89021 milliseconds
BufferedInputStream,BufferedOutputStream
The buffer stream reads an array of bytes one at a time -- taking a total of 47 milliseconds
The buffer stream reads one byte at a time ------- taking a total of 348 milliseconds
Requirements: read D://a.mp4 and copy the contents of this file to the copy.file under the current project Mp4 (first on then off)
public class CopyMp4 { public static void main(String[] args) { //Start time long start = System.currentTimeMillis() ; //copyMp4("D://a.mp4","copy.mp4") ; //copyMp4_2("D://a.mp4","copy.mp4") ; //copyMp4_3("D://a.mp4","copy.mp4") ; copyMp4_4("D://a.mp4","copy.mp4") ; //End time long end = System.currentTimeMillis() ; System.out.println("Total time"+(end-start)+"millisecond"); } //The buffer stream reads an array of bytes one at a time private static void copyMp4_4(String srcFile, String destFile) { BufferedInputStream bis = null ; BufferedOutputStream bos = null ; try { bis = new BufferedInputStream(new FileInputStream(srcFile)) ; bos = new BufferedOutputStream(new FileOutputStream(destFile)) ; //Read / write operation byte[] bytes = new byte[1024] ; int len = 0 ; while((len=bis.read(bytes))!=-1){ bos.write(bytes,0,len); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { bos.close(); bis.close(); } catch (IOException e) { e.printStackTrace(); } } } //The buffer stream reads one byte at a time private static void copyMp4_3(String srcFile, String destFile) { BufferedInputStream bis = null ; BufferedOutputStream bos = null ; try { bis = new BufferedInputStream(new FileInputStream(srcFile)) ; bos = new BufferedOutputStream(new FileOutputStream(destFile)) ; //Read / write operation int by = 0 ; while((by=bis.read())!=-1){ bos.write(by); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { bos.close(); bis.close(); } catch (IOException e) { e.printStackTrace(); } } } //The basic byte stream reads a byte array one at a time public static void copyMp4_2(String srcFile,String destFile){ //Encapsulate source and destination files FileInputStream fis = null ; FileOutputStream fos = null ; try { fis = new FileInputStream(srcFile) ; fos = new FileOutputStream(destFile) ; //Read write copy byte[] bytes = new byte[1024] ; int len = 0 ;//Actual bytes while((len=fis.read(bytes))!=-1){ fos.write(bytes,0,len); //Force the output stream to write out the number of bytes buffered fos.flush(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { fos.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } } //The basic byte stream reads one byte at a time public static void copyMp4(String srcFile, String destFile) { //Encapsulate source and destination files FileInputStream fis = null ; FileOutputStream fos = null ; try { fis = new FileInputStream(srcFile) ; fos = new FileOutputStream(destFile) ; //Read write copy int by = 0 ; while((by=fis.read())!=-1){ fos.write(by); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { fos.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Vi The character stream appears after the byte stream, which can solve the problem of Chinese garbled code
Writer: abstract class
Provide subclasses: character conversion output stream: a bridge between byte output stream and character output stream
Construction method
OutputStreamWriter(OutputStream out): writes data using the platform default encoding set
OutputStreamWriter(OutputStream out, String charsetName): writes data using the specified character set for encoding
public class WriterDemo { public static void main(String[] args) throws Exception { //Create character buffered output stream object OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("osw.txt")) ;//Use the platform's default encoding set (utf-8) //Write data /** * write(String str) * write(int ch):Write character: ASCII code table corresponding to character -- > * write(char[] ch) * write(char[] ch,int off,int len) * write(String str,int off,int len) */ osw.write("hello,I'm here"); osw.write(97); char[] chs = {'A','B','C','D','E'} ; osw.write(chs); osw.write(chs,2,2); //Use flush(): refresh the character output stream osw.flush(); //Close resources and release related resources osw.close(); //flush before closing } }
Reader: abstract class
Specific subclass: character conversion input stream InputStreamReader
Construction method
InputStreamReader(InputStream in): reads using the platform default decoding set
InputStreamReader(InputStream in,String charset): reads using the specified decoding set
public class test1 { public static void main(String[] args) throws IOException { InputStreamReader isr = new InputStreamReader(new FileInputStream("f:\\lhb.txt")); char[] chars = new char[1024]; int len = 0; while ((len=isr.read(chars))!=-1){ System.out.println(new String(chars,0,len)); } isr.close(); } }
Requirements:
When the LHB of disk f Txt file} copy to lhb2.txt under the current project txt
For text files: character stream is preferred
public class test1 { public static void main(String[] args) throws IOException { FileReader srcfile = new FileReader("f:\\lhb.txt"); FileWriter targerfile = new FileWriter("lhb2.txt"); /*int by = 0; while ((by=srcfile.read())!=-1){ targerfile.write(by); targerfile.flush(); }*/ char[] chars = new char[1024]; int len = 0; while((len = srcfile.read(chars))!=-1){ targerfile.write(chars,0,len); targerfile.flush(); } targerfile.close(); srcfile.close(); } }
BufferedReaer/BufferedWriter: read / write copy operation
Read one character at a time
Read one character array at a time
Unique features:
Read a line with BufferedReader's readLine()
Write a line with BufferedWriter and wrap it
Read write copy of a text file:
Blocking flow (traditional IO flow)
When a thread operates a read action, read (byte [] byte / char []..)/ Readline(): all are blocking methods
If the other thread operates a write action and the reading thread starts reading, the writing thread here can start the write copy operation
Requirements:
When the LHB of disk f Txt file} copy to lhb2.txt under the current project txt
public class test1 { public static void main(String[] args) { BufferedReader br = null; BufferedWriter bw = null; try { br = new BufferedReader(new FileReader("f://lhb.txt")); bw = new BufferedWriter(new FileWriter("lhb2.txt")); String line = null; while ((line=br.readLine())!=null){ bw.write(line); bw.newLine(); bw.flush(); } } catch (IOException e) { e.printStackTrace(); }finally { try { bw.close(); br.close(); } catch (IOException e) { e.printStackTrace(); } } } }
VII Read more than two files
public SequenceInputStream(Enumeration<? extends InputStream> e)
Vector<InputStream>
Add (add multiple byte input stream object)
Demand: LHB under disk f txt lhb2.txt lhb3.txt file and copy it to lhb4.txt in the current directory txt
public class test1 { public static <vector> void main(String[] args) throws IOException { InputStream is1 = new FileInputStream("f:\\lhb.txt"); InputStream is2 = new FileInputStream("f:\\lhb2.txt"); InputStream is3 = new FileInputStream("f:\\lhb3.txt"); Vector<InputStream> vector = new Vector<>(); vector.add(is1); vector.add(is2); vector.add(is3); Enumeration<InputStream> enumeration = vector.elements(); //Create a merge stream object to encapsulate the source file SequenceInputStream sis = new SequenceInputStream(enumeration); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("lhb4.txt")); int by = 0; while((by=sis.read())!=-1){ bos.write(by); bos.flush(); } bos.close(); sis.close(); } }