JavaIO programming
I/o system
File
Commonly used method | explain |
---|---|
mkdir | Creating a single directory |
mkdirs | Create multiple directories |
getPath | Gets the path to the file |
length | Gets the length of the file |
getName | Get file name |
getParentFile | Gets the upper directory of the file |
exists | Check whether the file exists |
createNewFile | Create a file |
list | Returns an array of strings naming files and directories in directories |
listFiles | Returns an array of abstract pathnames representing files in a directory represented by this abstract pathname |
getAbsolutePath | Returns an absolute pathname string for this abstract pathname |
File creation
Single file creation
@test // File creation public void IoFilePractise() throws IOException {File File = new File("D:\\file\\1.txt"); // Check whether the file directory existsif(! file.getParentFile().exists()) { System.out.println("D:\\file directory does not exist, create directory immediately"); file.getParentFile().mkdir(); } // Check whether 1. TXT existsif(! file.exists()) { System.out.println("1.txt file does not exist, create it now"); file.createNewFile(); }}Copy the code
Multilevel file creation
@Test
public void IoFilePractise3() throws IOException {
File file=new File("D:\\file\\B\\B1\\B2\\rose.txt"); // Create multiple hierarchical directoriesif(! file.getParentFile().exists()){ file.getParentFile().mkdirs(); } // create the rose.txt fileif(!file.exists()){
file.createNewFile();
}
}
Copy the code
File deletion
Delete the specified directory and files. It is worth noting that if you only delete the specified directory, there are other files or directories in the directory, it will not be able to delete successfully
@Test
public void IoFilePractise1() throws IOException {
File file = new File("D:\\file\\A\\jack.txt"); // Create A directory and jack.txt file file.getparentFile ().mkdir(); file.createNewFile(); // Try to delete the A directory file.getparentFile ().delete(); // Check whether directory A is successfully deletedif (file.getParentFile().exists()) {
System.out.println("Directory A has not been deleted");
} else {
System.out.println("Directory A was deleted successfully"); }}Copy the code
@test // Based on the above public voidIoFilePractise2() {
File file = new File("D:\\file\\A\\jack.txt"); file.delete(); file.getParentFile().delete(); // Check whether directory A is successfully deletedif (file.getParentFile().exists()) {
System.out.println("Directory A has not been deleted");
} else {
System.out.println("Directory A was deleted successfully"); }}Copy the code
Output file directory
Count D disk below all the file number and output the name, find all TXT files and output and statistics
private static int fileNumber = 0;
private static int txtFileNumber = 0;
private static int directoryNumber = 0;
@Test
public void IoFilePractise4() {
String filePath = "D:\\";
findFile(filePath);
System.out.println("Number of files:" + fileNumber);
System.out.println("Number of TXT files: + txtFileNumber);
System.out.println("Number of file directories:"+ directoryNumber); } public void findFile(String filePath) { File file = new File(filePath); File[] listFile = file.listfiles (); // Stop recursion if there are no files under the file directoryif(listFile==null)return; // recursive traversalfor(File fileTemp: listFile) {// If it is a Fileif (fileTemp.isFile()) {
fileNumber++;
System.out.println(fileTemp.getName() + "For file");
if (fileTemp.getName().endsWith(".txt")) {
txtFileNumber++;
System.out.println(fileTemp.getName() + "Also TXT file"); }}else if (fileTemp.isDirectory()) {
directoryNumber++;
System.out.println(fileTemp.getName() + "For file directory"); findFile(fileTemp.getPath()); }}}Copy the code
IO Basic Categories
Most of the methods of subclasses are inherited from the parent class, the parent class of the method is clear, the use of subclasses will be easily solved
InputStream class
methods | Methods to introduce |
---|---|
public abstract int read() | Read the data |
public int read(byte b[]) | Place the read data in a byte array |
public int read(byte b[], int off, int len) | Read len bytes of data from the off position into the byte array |
public void close() | After reading, close the stream and release the resource |
OutputStream class
methods | Methods to introduce |
---|---|
public abstract void write(int b) | Write a byte |
public void write(byte b[]) | Writes all the bytes in the array |
public void write(byte b[], int off, int len) | Writes len length bytes from the byte array starting at the off position |
public void close() | Close the output stream. The stream can no longer output data after it is closed |
Reader class
methods | Methods to introduce |
---|---|
public int read() | Reading a single character |
public int read(char cbuf[]) | Reads characters into the specified char array |
abstract public int read(char cbuf[], int off, int len) | Reads len characters from the off position into the char array |
abstract public void close() | Close the stream to release the associated resources |
Writer class
methods | Methods to introduce |
---|---|
public void write(int c) | Write a character |
public void write(char cbuf[]) | Writes to a character array |
abstract public void write(char cbuf[], int off, int len) | Writes len of characters from the off position of the character array |
abstract public void close() | Close the output stream. The stream can no longer output data after it is closed |
FileInputStream and FileOutputStream
Read byte by byte
@Test public void FileRead() throws IOException { int count=0; FileInputStream fis = new FileInputStream("D:\\file\\1.txt"); int len; // Read byte by byte and return -1 after readingwhile((len = fis.read()) ! = -1) { System.out.print((char)len); count++; } System.out.println("Count of reads :"+count);
fis.close();
}
Copy the code
Read multiple bytes at a time
@Test public void FileRead() throws IOException { int count=0; FileInputStream fis = new FileInputStream("D:\\file\\1.txt"); byte[] n=new byte[1024]; int len; // Read byte by byte and return -1 after readingwhile((len = fis.read(n)) ! // New String(byte[] bytes, int offset, int length) decodes the specified byte subarray using the platform's default character set, Construct a new String system.out.println (new String(n,0,len)); count++; } System.out.println("Count of reads :"+count);
fis.close();
}
Copy the code
File is written to
@test public void FileWrite() throws IOException {// Add FileOutputStream fos=new FileOutputStream("D:\\file\\1.txt".true); // Write a single byte fos.write(98); // Write multiple bytes fos.write(",Hello World!".getBytes());
fos.close();
}
Copy the code
File copy
TXT public void FileCopy() throws IOException {// If 1.txt and 2.txt files are not available, FileOutputStream fos=new must be created in advance FileOutputStream("D:\\file\\2.txt");
FileInputStream fis=new FileInputStream("D:\\file\\1.txt");
int len;
byte[] n=new byte[1024];
while((len=fis.read(n))! =-1){ fos.write(n,0,len); } fos.close(); fis.close(); }Copy the code
BuffereInputStream and BuffereOutputStream
Buffer stream copy
@test public void FileBuffer() throws IOException {// The object requiring FileInputStream and FileOutStream BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\file\\1.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\file\\2.txt"));
int len;
while((len = bis.read()) ! = -1){ bos.write(len); } bos.close(); bis.close(); }Copy the code
InputStreamReader and OutputStreamWriter
With copies in Chinese
@test public void FileStream() throws IOException {// Add: InputStreamReader isr=new InputStreamReader(new FileInputStream())"D:\\file\\1.txt"),"GBK");
OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("D:\\file\\2.txt"),"GBK");
int len;
char[] n=new char[1014];
while((len= isr.read(n))! =-1){ System.out.println(new String(n,0,len)); osw.write(n,0,len); } isr.close(); osw.close(); }Copy the code
The ObjectOutputStream and ObjectInputStream
ObjectOutputStream is serializing streams, ObjectInputStream is deserializing streams, Serializable interface must be implemented, otherwise Serializable interface cannot be serialized. If an attribute in an object has the transient and static keywords, it will not be serialized.
Write and read objects
import java.io.Serializable;
public class Book implements Serializable {
private String id;
private String name;
private int money;
private transient int weight;
@Override
public String toString() {
return "Book{" +
"id='" + id + '\'' + ", name='" + name + '\'' + ", money=" + money + ", weight=" + weight + '}'; } public Book(String id, String name, int money, int weight) { this.id = id; this.name = name; this.money = money; this.weight = weight; } ----- getter and setter----- } @Test public void ObjectTest() throws IOException, ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\file\\1.txt", true)); oos.writeInt(99); oos.writeObject(new Book("001","My Chinese dream", 100,)); oos.close(); Ois = new ObjectInputStream(new FileInputStream("D:\\file\\1.txt")); int readInt = ois.readInt(); Book book = (Book) ois.readObject(); System.out.println(readInt); System.out.println(book); ois.close(); }Copy the code
At the end
As a Java beginner, to understand IO to this point is almost the same, the back can be based on interest or actual needs of the project to continue to learn. I myself am also a Java rookie, still in school, Java foundation is very poor, write blog is mainly with the mentality of learning, if there is something wrong in the above hope to point out.