当前位置:网站首页>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
边栏推荐
- 什么是骨干网
- Blue Bridge Cup - practice system login
- Detailed explanation of IVX low code platform series -- Overview (I)
- Day_ 05
- Bombard the headquarters. Don't let a UI framework destroy you
- error Parsing error: Unexpected reserved word ‘await‘.
- What is backbone network
- Built in function globals() locals()
- DINO: DETR with Improved DeNoising Anchor Boxes for End-to-End Object Detection翻译
- 完美洗牌问题
猜你喜欢

Interviewer: your resume says you are proficient in mysql, so you say cluster / Union / overlay index, table return, index push down

Understanding of reflection part

Kettle表输入组件精度丢失的问题

Dino: Detr with improved detecting anchor boxes for end to end object detection

Record learning of hystrix knowledge --20210929

GO语言-锁操作

Uncover gaussdb (for redis): comprehensive comparison of CODIS

不要小看了积分商城,它的作用可以很大!

Go language - what is critical resource security?

Xinlou: un voyage de sept ans de Huawei Sports Health
随机推荐
The first day of reading mysql45
What can one line of code do?
一文带你搞懂 JWT 常见概念 & 优缺点
【NLP】今年英语高考,CMU用重构预训练交出134高分,大幅超越GPT3
Interviewer: your resume says you are proficient in mysql, so you say cluster / Union / overlay index, table return, index push down
Div element
加密潮流:时尚向元宇宙的进阶
Android修行手册之Kotlin - 自定义View的几种写法
Don't underestimate the integral mall, its role can be great!
The style of the mall can also change a lot. DIY can learn about it!
This article will help you understand the common concepts, advantages and disadvantages of JWT
Helsinki traffic safety improvement project deploys velodyne lidar Intelligent Infrastructure Solution
根据先序遍历和中序遍历生成后序遍历
炮打司令部,别让一个UI框架把你毁了
Deadlock, thread communication, singleton mode
Hash table, generic
Webgl and webgpu comparison [4] - uniform
Don't underestimate the integral mall, its role can be great!
【效率】又一款笔记神器开源了!
Error: homebrew core is a shallow clone