当前位置:网站首页>IO stream
IO stream
2022-06-25 16:26:00 【[email protected]】
List of articles
1.File The use of the class
- File Can be built 、 Delete 、 Rename files and directories , But you can't access the contents of the file
- File Object can be passed as a parameter to the constructor of the stream
public File(String pathname)Create with specified path File objectpublic File(String parent,String child)With parent The path of fatherhood ,child Create... For the subpath file objectpublic File(File parent,String child)According to a father File Object and sub file path creation File object
package javabasis.chapter13;
import java.io.File;
import java.io.IOException;
public class FileTest {
public static void main(String[] args) throws IOException {
File dir1=new File("dir1");// Construction method 1
if(!dir1.exists())// If not, create a directory
dir1.mkdir();//mkdir Only single level path files can be created , What if the upper level directory doesn't exist , The current file will not be created
// establish dir1 Under the parent directory dir2 object
File dir2=new File(dir1, "dir2");// Construction method 2
// Create a directory if it does not exist
if(!dir2.exists())
dir2.mkdirs();
File dir4=new File(dir1, "dir3/dir4");
if(!dir4.exists())
dir4.mkdirs();//mkdirs You can create dir3/dir4 This multi-level path
// Get the... Under the specified path text.txt object
File file=new File("D:/VS_Code_Java/dir1", "test.txt");// Construction method 3
// If it does not exist, it is created as a file type ( Not a directory )
if(!file.exists())
file.createNewFile();
// Use of methods
//1. Get absolute path
System.out.println(file.getAbsolutePath());//D:\VS_Code_Java\dir1\test.txt
//2. Get path
System.out.println(dir4.getPath());//dir1\dir3\dir4
//3. Get the name
System.out.println(file.getName());
//4. Get the upper directory file
System.out.println(file.getParent());
//5. Get file length
System.out.println(file.length());// Only documents , It can't be a catalog
//6. Determine whether it is a file directory
System.out.println(file.isDirectory());
//7. Determine if it's a document
System.out.println(file.isFile());
}
}
2.IO Flow principle and classification of flow
- Input : Transfer external data ( disk 、 Compact disc ) The data in is read into memory
- Output : Store the data output from memory to disk 、 On the CD
- Four base classes :
- Byte input stream InputStream
- Byte output stream OutputStream
- Character input stream Reader
- Character output stream Writer
3. Node flow ( File stream )
- Byte input stream FileInputStream
- Byte output stream FileOutputStream
- Character input stream FileReader
- Character output stream FileWriter
package javabasis.chapter13;
import java.io.File;
import java.io.FileReader;
public class FileReaderTest {
public static void main(String[] args) {
FileReader fr=null;
try {
fr=new FileReader(new File("D:/VS_Code_Java/dir1/test.txt"));// The path uses / or \\
char buf[]=new char[1024];
int len;
while((len=fr.read(buf))!=-1)
System.out.println(new String(buf,0,len));
} catch (Exception e) {
System.out.println(e.getMessage());
}finally{
if(fr!=null)
{
try {
fr.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
}
}
package javabasis.chapter13;
import java.io.File;
import java.io.FileWriter;
public class FileWriterTest {
public static void main(String[] args) {
FileWriter fw=null;
try {
fw=new FileWriter(new File("D:/VS_Code_Java/dir1/test.txt"),true);
// add true Will add... At the end of the original file If not, the contents of the original file will be overwritten
fw.write("today is Monday");
} catch (Exception e) {
e.printStackTrace();
}finally{
if(fw!=null)
{
try {
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
4. Buffer flow ( Processing flow )
- Buffered streams can improve the speed of data reading and writing
- The buffer stream should be nested on the corresponding node stream
- BufferedInputStream
- BufferedOutputStream
- BufferedReader
- BufferedWriter
- When reading data using a buffered stream , The buffer stream will read a certain file from the file at one time and store it in the buffer , Read again from the file until the buffer is full
- When writing bytes using a buffered stream , Will not be written directly to the file , Write to buffer first , The buffer is full , The data in the buffer is written to the file at one time
- Use flush You can manually turn buffer Content in write to file
package javabasis.chapter13;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
public class BufferStreamTest {
public static void main(String[] args) {
BufferedReader br=null;
BufferedWriter bw=null;
try {
br=new BufferedReader(new FileReader("D:/VS_Code_Java/javabasis/chapter13/source.txt"));
bw=new BufferedWriter(new FileWriter("D:/VS_Code_Java/javabasis/chapter13/desc.txt"));
String str;
while((str=br.readLine())!=null)// Read one line at a time
{
bw.write(str);
bw.newLine();
}
bw.flush();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(bw!=null)
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if(br!=null)
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
5. Converted flow ( Processing flow )
- Realize the conversion between byte stream and character class
- InputStreamReader: take InputStream Turn into Reader
- OutputStreamWriter: take Writer Turn into OutputStream
package javabasis.chapter13;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class TransStream {
public static void main(String[] args) throws Exception {
// Create a byte stream
FileInputStream fin=new FileInputStream("D:/VS_Code_Java/javabasis/chapter13/source.txt");
FileOutputStream fout=new FileOutputStream("D:/VS_Code_Java/javabasis/chapter13/desc.txt");
InputStreamReader byte2char=new InputStreamReader(fin,"UTF-8");// Byte stream ---> Character stream The codes shall be consistent Otherwise, there will be confusion
OutputStreamWriter char2byte=new OutputStreamWriter(fout,"UTF-8");// Character class ---> Byte stream
BufferedReader br=new BufferedReader(byte2char);
BufferedWriter bw=new BufferedWriter(char2byte);
String str=null;
while((str=br.readLine())!=null)
{
bw.write(str);
bw.newLine();
bw.flush();
}
bw.close();
br.close();
}
}
6. Object flow
- ObjectInputStream
- ObjectOutputStream
- serialize : use ObjectInputStream preservation Object or base type
- Deserialization : use ObjectOutputStream Read Object or base type
- ObjectInputStream ObjectOutputStream Cannot serialize static and transient Modified member variables
- Conditions for object serialization : Realization Serializable or Externalizable Interface one
- If there are other reference types in the object (String With the exception of ), The reference type must also implement Serializable Interface
- Basic data type
package javabasis.chapter13;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class SerializableTest {
public static void main(String[] args) throws Exception, IOException {
// serialize
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("D:/VS_Code_Java/javabasis/chapter13/Person.txt"));
Person p1=new Person("Mike", 11, new Pet("dog"));
Person p2=new Person("Tom", 12, new Pet("cat"));
out.writeObject(p1);
out.writeObject(p2);
out.flush();
out.close();
// Deserialization
ObjectInputStream in=new ObjectInputStream(new FileInputStream("D:/VS_Code_Java/javabasis/chapter13/Person.txt"));
Person p3= (Person) in.readObject();
Person p4= (Person) in.readObject();
System.out.println(p3);
System.out.println(p4);
}
}
class Person implements Serializable{
String name;
int age;
Pet pet;
public Person(String name,int age,Pet pet)
{
this.name=name;
this.age=age;
this.pet=pet;
}
public String toString()
{
return "name:"+name+" age:"+age+" "+pet;
}
}
class Pet implements Serializable{
String name;
public Pet(String name)
{
this.name=name;
}
public String toString()
{
return "pet:"+name;
}
}
name:Mike age:11 pet:dog
name:Tom age:12 pet:cat
7. Random access file stream
package javabasis.chapter13;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
public class RandomAccessFileTest {
public static void main(String[] args) throws Exception {
RandomAccessFile raf=new RandomAccessFile("javabasis/chapter13/source.txt", "rw");
raf.seek(2);// Navigate to a location in the file and start reading
byte b[]=new byte[1024];
raf.read(b,0,5);
System.out.println(new String(b,0,5));
raf.close();
}
}
版权声明
本文为[[email protected]]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202190532338147.html
边栏推荐
- Uniapp converts graphic verification codes in the form of file streams into images
- Mt60b1g16hc-48b:a micron memory particles FBGA code d8bnk[easy to understand]
- 加密潮流:时尚向元宇宙的进阶
- flutter
- Flutter assembly
- DINO: DETR with Improved DeNoising Anchor Boxes for End-to-End Object Detection翻译
- User registration, information writing to file
- White screen, how fouc is formed, and how to avoid it
- Dino: Detr with improved detecting anchor boxes for end to end object detection
- GridLayout evenly allocate space
猜你喜欢

What plug-ins are available for vscade?

20省市公布元宇宙路线图

mysql整体架构和语句的执行流程

Read mysql45 lecture - index

DINO: DETR with Improved DeNoising Anchor Boxes for End-to-End Object Detection翻译

The style of the mall can also change a lot. DIY can learn about it!

【效率】又一款笔记神器开源了!

Understanding of reflection part

Alvaria宣布客户体验行业资深人士Jeff Cotten担任新首席执行官

Advanced SQL statement 1 of Linux MySQL database
随机推荐
This article will help you understand the common concepts, advantages and disadvantages of JWT
Educational administration system development (php+mysql)
f_ Read function [easy to understand]
What is the NFT digital collection?
Swift responsive programming
JS add custom attributes to elements
20省市公布元宇宙路线图
The style of the mall can also change a lot. DIY can learn about it!
Activation and value transfer of activity
One minute to familiarize yourself with the meaning of all fluent question marks
The first day of reading mysql45
Flutter textfield setting can input multiple lines
心樓:華為運動健康的七年築造之旅
Unity技术手册 - 生命周期旋转RotationOverLifetime-速度旋转RotationBySpeed-外力ExternalForces
Based on neural tag search, the multilingual abstracts of zero samples of Chinese Academy of Sciences and Microsoft Asiatic research were selected into ACL 2022
Built in function globals() locals()
八种button的hover效果
Day_ thirteen
User login 2
Bugly hot update usage