Re-start learning Java-File And Streams

Note: This article only describes the basic usage, and does not touch on the NIO, the NIO aspects of things, described in a later blog. Random Access File is placed before it is described.

File

In the filename system, the filename is used to locate the storage location metadata: the data describing the data, where we treat a file as a data, then the attribute of the file is metadata.

The java.io.File class represents files and directories unrelated to the current system platform

An instance of the File class represents a file or directory.

The File class provides a way to determine whether an instance is a file or a directory.

File class provides a way to manipulate files and directories in a file system

File classes only represent files or directories and do not support modifying the contents of files

Construction method

File( String pathname )
Create a new File instance by converting a given path name string to an abstract path name

File( String parent , String child )
Create a new File instance based on parent path name string and child path name string

File( File parent , String child )
Create a new File instance based on parent Abstract path name and child path name string

File( URI uri )
Create a new File instance by converting a given file: URI to an abstract path name

But when we use it, the File construction method of passing a path is the most frequently used method.

constant

public static final char separatorChar
 Default name delimiters associated with the system (delimiters between paths at different levels in the file system)

public static final String separator
 The default name delimiter associated with the system is represented as a string for_

public static final char pathSeparatorChar
 System-related path separators (separators between different parts of the value of environmental variable PATH)

public static final String pathSeparator
 The path separator associated with the system is represented as a string for _________________.

Method test

    String path = "C:/Windows/notepad.exe" ;
	// Create an object representing the Java object of the directory based on the path of the given directory
	File directory = new File(path) ; 
	System.out.println("File Does the directory or file represented exist:" + directory.exists() );
	System.out.println("Is it a document? " + directory.isFile() );
	System.out.println( "Is it a directory? " + directory.isDirectory() );
	System.out.println("Is it hidden?" + directory.isHidden() );
	System.out.println("Is it an absolute path?" + directory.isAbsolute() );
	// The number of bytes returned by the length method needs to be converted to KB or other units (valid only for files, invalid for directories)
	System.out.println("The length of the file is:" + directory.length()/1024 );
	path = "C:\\JavaApplication\\mysql-5.7.17-winx64" ; 
	directory = new File( path ) ; 
	String[] names = directory.list() ;
	for (String s : names) {
		System.out.print(s + "\t");
	}
	System.out.println();
	File[] fileNames = directory.listFiles() ;
	for (File f : fileNames) {
		System.out.print(f.toString() + "\t");
	}
	System.out.println();
	
	path = "C:/Windows/notepad.exe" ;
	File f = new File(path) ; 
	System.out.println("File name or directory name: " + f.getName() );
	System.out.println("Storage path: " + f.getParent() );
	System.out.println("Absolute path:" + f.getAbsolutePath() );
	System.out.println("Last modified milliseconds:" + f.lastModified() );
	System.out.println( "Time for final revision:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date( f.lastModified() )));
	System.out.println("Is the file or directory readable?" + f.canRead() );
	System.out.println("Is a file or directory writable?" + f.canWrite() );
	System.out.println("Does a file or directory execute:" + f.canExecute() );
		
	/**
	 * Running Java programs with main methods in Eclipse environment, the default current path is the current project
	 * Attention to the Normalized Form of Path
	 */
	path = "." ;
	f = new File( path ) ; 
	System.out.println( f.getAbsolutePath() );
	path = "src" ;// Represents the src directory under the current path
	f = new File( path ) ; 
	System.out.println( "Get the absolute path:" + f.getAbsolutePath() );
	f = new File("..");
	System.out.println( "Get the absolute path:" + f.getAbsolutePath() );
	System.out.println("Get the path of normalized form:" + f.getCanonicalPath() );
	f = new File( "/" ) ;
	System.out.println(f.getAbsolutePath() );
	System.out.println(f.getCanonicalFile());
	/**
	 * Create new files, delete new files
	 */
	path = "." ;
	f = new File( path ) ; 
	if( f.canWrite() ) {
		// Create a hello.txt file in the directory corresponding to f
	    // Create a Java object in memory that represents the file corresponding to hello.txt under f
		File file = new File( f , "hello.txt") ;
		if ( file.exists()) {
			file.delete() ; 
		}
		// Create a new file corresponding to the file object on disk
		boolean b = file.createNewFile() ;
		System.out.println( b );// Failed to create if permissions already exist or do not exist
		
	}
	/**
	 * Create and delete directories (delete can delete empty directories)
	 */
	if( f.canWrite() ) {
		File file = new File( f , "kaka") ; 
		if( file.exists() && file.isDirectory()  ) {
			boolean b = file.delete() ;
			System.out.println( b ? "Successful directory deletion" : "Directory deletion failed" );
		}
		boolean b = file.mkdir() ; // create a new directory
		System.out.println( b ? "Directory Creation Successful" : "Directory creation failed");
	}
	/**
	 * mkdir You can create a subdirectory
	 * mkdirs You can create multiple subdirectories
	 */
	if( f.canWrite() ) {
		File file = new File( "kaka/kakaTM/kakTTMM");
		file.mkdirs() ;
		File dest = new File("kaka/kakaTM/kakTTMMMM") ; 
		// Rename the name of the file to the name corresponding to dest
		file.renameTo(dest) ; 
	}
	
	File s = new File("./hello.txt") ; 
	File d = new File("C:/abc.txt") ; 
	s.renameTo(d) ; // Cut operation (strongly not recommended)
	File kak = new File("kaka") ; 
	kak.deleteOnExit(); // Delete the virtual machine after it exits
	Thread.sleep(30000 );// You can test it here.

File filter

It can be filtered according to conditions (final modification time, length, name, etc.).

File dof = new File("C:/test") ; 
	if( dof.exists() && dof.isDirectory() ) {
		FilenameFilter fnf = new FilenameFilter() {
			[@Override](https://my.oschina.net/u/1162528)
			public boolean accept(File dir, String name) {
				if( name.endsWith("java")) {
					return true ; 
				}
				return false;
			}
		};
		String[] fileList = dof.list(fnf) ;
		System.out.println( fileList.length );
		for (String s : fileList) {
			System.out.println( s );
		}
	}
File dof = new File("C:/test") ; 
	if( dof.exists() && dof.isDirectory() ) {
		FileFilter fnf = new FileFilter() {
			
			[@Override](https://my.oschina.net/u/1162528)
			public boolean accept(File pathname) {
				if( pathname.isFile() && pathname.getName().endsWith(".java")) {
					return true ; 
				}
				return false;
			}
		};
		File[] fileList = dof.listFiles(fnf);
		System.out.println( fileList.length );
		for (File s : fileList) {
			System.out.println( s );
		}
	}

Exercise: You can get the names of all the files on CD C through traversal.

Byte input-output stream

InputStream is the parent of all byte input streams.

Pay attention to the structure

We can use FileInputStream to test the methods in InputStream

    File file = new File("out.txt") ; 
	InputStream inStream = null ; 
	System.out.println( inStream );
	if( file.exists() && file.isFile() ) {
		inStream = new FileInputStream(file) ; 
		System.out.println( inStream );
//		int b = inStream.read(); // Range 0 - 255, translate byte numbers into int values
//		System.out.println( b );
		int b ; 
		do {
			// The read method reads a byte.
			// If the end of the stream is not reached, the read data is returned.
			// If it reaches the end of the stream, it returns - 1
			b = inStream.read() ; // Read one byte at a time
			System.out.println( b );
		}while( b!=-1 );
		
	}
	inStream.close();

Here read a byte at a time, parse out all the numbers, if converted to char type, do not understand. So you can use arrays to indicate how many bytes are read at a time.

    File file = new File("out.txt") ; 
    InputStream inStream = null ; 
	System.out.println( inStream );
	if( file.exists() && file.isFile() ) {
		inStream = new FileInputStream(file) ; 
		System.out.println( inStream );
		// The estimated number of bytes that can be read from this input stream without blocking until the next call method is obtained
		int size = inStream.available() ; 
		byte[] bytes = new byte[size] ; 
		int n ; 
		/*do {
			// read( byte[] bytes )Method is responsible for reading n bytes.
			// If it does not reach the end of the stream, it returns the number of bytes read (a few bytes read back)
			// If the content is read, the bytes read are put into the array (if read several, put several)
			// If it reaches the end of the stream, it returns - 1
			n = inStream.read(bytes ) ; // Read one byte at a time
			System.out.println( "The number of bytes read: "+n";
			String s = new String(bytes , 0 , n ) ; 
			System.out.println( s );
		}while( n!=-1 );
		*/
		while( (n = inStream.read(bytes)) != -1 ) {
			String s = new String( bytes , 0 , n) ; 
			System.out.println( s );
		}
	}
	System.out.println( inStream.markSupported() );
	inStream.close(); 

We can see that FileInputStream does not support tagging, let's talk about it later. So our FileInput Stream is finished.

FileOutputStream

This abstract class is a superclass representing all classes of the output byte stream. The output stream accepts the output bytes and sends them to a receiver.

Applications that need to define subclasses of OutputStream must always provide at least one way to write an output byte.

        public static void main(String[] args) throws Exception {
		File file = new File("file.txt") ;// The first parameter indicates where the output goes. 
		boolean append = false ; // If the second parameter is true for additions and false for overrides
		OutputStream os = new FileOutputStream(file, append) ;
		// Output of a single byte (if it is an integer of type int, it ignores the high 24 bits, leaving only the low 8 bits)
		os.write(97);
		os.write(378);
		byte[] bytes = "Kaka his mother".getBytes() ;
		System.out.println( bytes.length );
		// Output the byte array to the file through the output stream
		os.write(bytes);
		// Output part of the byte array to write (bytes, start, n) [start, start + n]
		os.write(bytes,3 , 3);
		os.close();
	}

In this way, we will use the methods in the OutputStream class.

Copy file

    public static void main(String[] args) throws Exception {
		File source = new File("G:\\Zen Zen wallpaper\\Wallpaper\\Desktop Background 03.jpg") ; 
		File target = new File( source.getName() ) ; 
		FileInputStream in = new FileInputStream(source) ; 
		FileOutputStream out = new FileOutputStream( target ) ;
		int n ; // Declare a variable to record the number of bytes read
		byte[] bytes = new byte[128] ; 
		while( (n = in.read(bytes ) ) != -1 ) {
//			out.write(bytes);
			out.write(bytes, 0, n);
		}
		out.close();
		in.close();
	}

Of course, we can take a look at the replication time.

BufferedInputStream

BufferedInputStream adds some functionality to another input stream, namely, the ability to buffer input and support mark and reset methods. When you create BufferedInputStream, you create an internal buffer array.

    public static void main(String[] args) throws Exception {
		InputStream in = new FileInputStream("src/bufferedStream/TestBufferedStream1.java") ; 
		// super(in)--->this.in = in ; 
		// this.buf = new byte[8192]; // There is an array of bytes inside
		BufferedInputStream bis = new BufferedInputStream(in) ;
		byte[] bytes = new byte[100] ; 
		int n;
		while((n=bis.read(bytes))!=-1 ) {
			String s = new String( bytes , 0 , n );
			System.out.print(s);
		}
		bis.close();
		in.close();
	}
    public static void main(String[] args) throws Exception {
		InputStream in = new FileInputStream("bufferIn.txt") ; 
		BufferedInputStream bis = new BufferedInputStream(in) ;
		int n;
		while((n=bis.read())!=-1 ) {
			char ch = (char)n;
			System.out.print( ch );
			if( bis.markSupported() ) {// Determine whether mark and reset operations are supported
				if(ch=='s') {
					// this.marklimit = readlimit;// this.maklimit =250 
			        // this.markpos = pos;
					bis.mark(250);
				}
			}
		}
		System.out.println();
		if(bis.markSupported() ) {
			bis.reset();
			int b;
			while((b=bis.read())!=-1 ) {
				char ch = (char)b;
				System.out.print( ch );
				
			}
		}
		bis.close();
		in.close();
	}
/**
 * Output of data to the buffer byte output stream, without close and flush methods, may result in data not being output
 */
public class TestBufferedStream3 {
	public static void main(String[] args) throws Exception {
		OutputStream out = new FileOutputStream("buffer.txt") ; 
		BufferedOutputStream bos = new BufferedOutputStream(out) ;
		bos.write(97);
		bos.write('b');
		bos.write(100);
		// Call the flush method to brush out the contents of the buffer
		// bos.flush();
		bos.close();// The flush method is called in the close method
	}
}

Character Input and Output Stream

Reader

An abstract class for reading character streams. The only methods that subclasses must implement are read(char[], int, int) and close(). Because it's an abstract class, you can't find a new object. You can find its subclass: FileReader

public class TestReader {
	public static void main(String[] args) throws Exception {
		String file = "src/reader/TestReader.java" ;
		// Create a character input stream that reads one character at a time
		Reader reader = new FileReader(file) ; 
		int ch ; 
		// read() in Reader can return a character (in integer form)
		// If you read to the end of the stream, return - 1
		while( (ch = reader.read() ) != -1 ) {
			// Mandatory conversion of characters in integer form to char type
			char c = (char)ch ; 
			System.out.print(c);
		}
	}
}
    public static void main(String[] args) throws Exception {
		String file = "src/reader/TestReader2.java" ;
		Reader reader = new FileReader(file) ; 
		char[] chars = new char[100] ;// Represents 100 words
		int ch ; 
		// read(char[] charArray) in Reader can read n bytes from a stream into an array
		while( (ch = reader.read( chars ) ) != -1 ) {
			// Construct the character read this time into a string
			String s = new String(chars, 0, ch) ; 
			System.out.print(s);
		}
		reader.close();
	}

Writer

    public static void main(String[] args) throws Exception {
		String filename = "writer.txt" ; 
		boolean append = false ; 
		Writer w = new FileWriter(filename , append ) ; 
		w.write(97);
		w.write('\n');
		w.write("helloworld");
		w.write('\n');
		char[] chars = {'k','k','T','M'} ; 
		w.write(chars);
		w.write(chars, 2,1 );
		w.close();
	}
    public static void main(String[] args) throws Exception {
		String filename = "writer.txt" ; 
		boolean append = false ; 
		Writer w = new FileWriter(filename , append ) ; 
		w.append("hello") ; 
		w.append('k') ; 
		w.write("TM");
		w.close();
	}

BufferedReader&&BufferedWriter

    public static void main(String[] args) throws Exception {
		// Create a character input stream (node stream) that reads the contents of the file
		Reader r = new FileReader("buffer.txt") ;
		// Create a character input stream with buffering (it provides additional functionality)
		// A char array that can hold 8192 characters inside the BufferedReader instance
		BufferedReader br = new BufferedReader( r ) ; 
		String s ; 
		while( (s = br.readLine() ) != null ) {
			System.out.println( s );
		}
		br.close();
		r.close();
	}
    public static void main(String[] args) throws Exception {
		Writer w = new FileWriter("buffer.txt");
		// BufferedWriter has an array of chars that can hold 8192 characters
		BufferedWriter bw = new BufferedWriter(w) ;
		bw.write("hello,kaka");// Write content to the buffer
		// Brush out the contents of the buffer to the target output stream
		bw.flush();
		bw.close();
		w.close();
		System.out.println( w.toString() );
	}

InputStreamReader && OutputStreamWriter

These two streams are the corresponding conversion streams, which are the conversion between byte stream and character stream.

/**
 *Input Stream Reader converts byte input stream into character input stream 
 */
public class TestInputStreamReader1 {
	public static void main(String[] args) throws Exception {
		String fileName = "src/conver/TestInputStreamReader1.java";
		// Create a byte input stream
		InputStream in = new FileInputStream(fileName) ;
		// Converting a byte input stream to a character input stream
		InputStreamReader isr = new InputStreamReader(in) ; 
//		byte[] bytes = new byte[8] ; 
//		int b ; 
//		while( (b = in.read(bytes)) != -1 ) {
//			String s = new String( bytes , 0 , b );
//			System.out.print(s);
//		}
		int n ; 
		// Read a character at a time (returned as an integer), save it in the ch variable, and then compare whether it is equal to - 1 (if it is - 1, it means the end)
		while( (n = isr.read()) != -1 ) {
			System.out.print( (char)n );
		}
		in.close();
	}
}
    public static void main(String[] args) throws Exception {
		// Store the standard input stream in the variable in
		InputStream in = System.in ; 
//		int n ;
//		while( (n = in.read() ) != -1 ) {
//			System.out.println((char)n);
//		}
		// Converting Byte Input Stream to Character Input Stream
		InputStreamReader r = new InputStreamReader(in ) ; 
		int ch ;
		while( (ch = r.read() ) != -1 ) {
			System.out.print((char)ch);
		}
		r.close();
		in.close();
		
	}
    public static void main(String[] args) throws Exception {
		// Store the standard input stream in the variable in
		InputStream in = System.in ; 
		// Converting Byte Input Stream to Character Input Stream
		InputStreamReader r = new InputStreamReader(in ) ; 
		// Wrap a character buffer stream
		BufferedReader br =new BufferedReader(r) ;
		String ch ; 
		while( (ch =  br.readLine() ) != null ) {
			
			System.out.print(ch);
			if( "byebye".equalsIgnoreCase(ch)) {
				System.exit(0);
			}
		}
		r.close();
		in.close();
	}

OutputStreamWriter

    /**
 * Converting character output stream to byte output stream
 */
public class TestOutputStreamWriter {
	public static void main(String[] args) throws IOException {
		// Create a byte output stream and output it to a text file
		OutputStream o = new FileOutputStream("convert.txt");
		// Converting character output stream to byte output stream
		OutputStreamWriter osw = new OutputStreamWriter( o ) ; 
		osw.write("Ha ha ha ha ha ha ha");
		osw.write('k');
		osw.write('\n');
		osw.close();
		o.close();
	}
}
/**
 *Read a UTF-8 encoding file, convert it to GBK encoding, and re-export it to another file
 */
public class TestOutputStreamWriter2 {
	public static void main(String[] args) throws IOException {
		// Read a text file
		InputStream inStream = new FileInputStream("convert.txt") ;
		// Create a transformation stream and specify the corresponding byte input stream and encoding name
		// When converting bytes into characters, the encoding specified by the encoding name is used.
		InputStreamReader isr = new InputStreamReader( inStream ,"UTF-8" ) ;
		// Create a byte output stream that can output bytes to a specified file
		OutputStream outputStream = new FileOutputStream("convert-gbk.txt");
		// Create a conversion stream (byte to character) with the specified byte stream as the output target
		// And specify the encoding name to use when converting characters into bytes
		OutputStreamWriter osw = new OutputStreamWriter(outputStream, "GBK") ; 
		int ch ;
		// Read a character at a time from the character input stream
		while( ( ch = isr.read() ) != -1 ) {
			// Re-output read characters through character output stream
			osw.write(ch); // Write a single character out to the Writer stream
		}
		osw.close();
		outputStream.close();
		isr.close();
		inStream.close();
	}
}

Object serialization

/**
 * If you want to complete serialization, you need to implement the java.io.Serializable interface
 */
public class Student implements Serializable{
	/**
	 * serialVersionUID Identity card number equivalent to a class
	 * When serialized, the number is output to the corresponding stream together
	 * When deserialized (read the stream restore object), the corresponding class is checked for existence (the number is checked)
	 */
	private static final long serialVersionUID = -3227384916215757351L;
	private Integer id ; 
	private String name ;
	private char gender ; 
	private Date bithdate ;
	// getter and setter
	}
/**
 * Serialization
 * Output a Java object to a stream in a specific sequence of bytes
 * Implemented by the ObjectOutputStream class writeObject(obj)
 * The class corresponding to the object being written needs to implement the java.io.Serialization interface
 */
public class ObjectSerialization1 {
	public static void main(String[] args) throws IOException {
		final Calendar c = Calendar.getInstance() ;
		Student s = new Student() ; 
		s.setId(9527);
		s.setName("Huaan");
		s.setGender('male');
		c.set(1888, 8, 8, 8, 8, 8);
		s.setBithdate(c.getTime());
		OutputStream out = new FileOutputStream("student.obj") ; 
		ObjectOutputStream oos = new ObjectOutputStream(out) ; 
		// Save Student Objects
		oos.writeObject(s);
		oos.close();
		out.close();
	}
}
/**
 * Deserialize
 * It is to read the data in a stream and restore (reconstruct) it to the corresponding object.
 * When refactoring, the serialVersionUID of the class corresponding to the object is checked
 * Deserialization is achieved through ObjectInputStream
 */
public class ObjectDeserialization1 {
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		InputStream in = new FileInputStream("student.obj") ; 
		ObjectInputStream ois = new ObjectInputStream(in) ; 
		// Reading the corresponding data of an object from a known byte stream
		Object o = ois.readObject() ;
		System.out.println( o );
		if( o instanceof Student) {
			Student s = (Student) o ; 
			System.out.println( s.getName() );
		}
		ois.close();
		in.close();
	}
}

Keywords: Programming Java encoding Windows Attribute

Added by shalinik on Tue, 17 Sep 2019 12:34:29 +0300