当前位置:网站首页>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
边栏推荐
- Several ways of SQL optimization
- 【NLP】今年英语高考,CMU用重构预训练交出134高分,大幅超越GPT3
- Navicat Premium 15 for Mac(数据库开发工具)中文版
- AutoK3s v0.5.0 发布 延续简约和友好
- Helsinki traffic safety improvement project deploys velodyne lidar Intelligent Infrastructure Solution
- [Third Party framework] retrofit2 (2) - add point configuration of network access framework
- 20省市公布元宇宙路线图
- Why does golang's modification of slice data affect the data of other slices?
- Day_ fifteen
- Lecun predicts AgI: big model and reinforcement learning are both ramps! My "world model" is the new way
猜你喜欢

Read mysql45 the next day

Describe your understanding of the evolution process and internal structure of the method area

Reading mysql45 lecture - index continued

深入理解和把握数字经济的基本特征

Understanding of reflection part

Understand the execution sequence of try catch finally in one diagram

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

Unity技术手册 - 生命周期内大小(Size over Lifetime)和速度决定大小(Size by Speed)

Coredata data persistence

What can one line of code do?
随机推荐
First knowledge of database
ES6 deconstruction assignment rename
Read AFN through - from the creation of manager to the completion of data parsing
数据存储和传输文件之XML使用和解析详解
DOM event flow, event delegate
2021, committed to better development
File operation, serialization, recursive copy
Don't underestimate the integral mall, its role can be great!
flutter
Flutter textfield setting can input multiple lines
Record learning of hystrix knowledge --20210929
Native JS dynamically add elements
Describe your understanding of the evolution process and internal structure of the method area
leetcode-8. String to integer (ATOI)
Power representation in go language
Day_ ten
Div element
When inputting text in the shutter textfield, if the page is refreshed, the cursor position will change.
Bombard the headquarters. Don't let a UI framework destroy you
【机器学习】基于多元时间序列对高考预测分析案例