当前位置:网站首页>File processing (IO)
File processing (IO)
2022-07-27 05:10:00 【My code!】
1.File Use of objects
1.1File Object description
- File class It is the abstract representation of files or folders in the current system
- Generally speaking Is the use of File object To operate the files or folders in our computer system
- Study File class It's really just through file Object to file in the system / Add, delete, change and check the folder
- All in all :File: File object , Used to represent folders or data files on disk
Method or constant
type
describe
public File(String filename)
Construction method
establish File Class object and pass in the full path
public boolean createNewFile()
Method
Create a new file
public boolean delete()
Method
Delete file
public boolean exists()
Method
Judge whether the file exists
public boolean isDirectory()
Method
Determine whether the given path is a directory
public long length()
Method
Returns the size of the file
public String[] list()
Method
List all the contents of the specified directory , List only names
public File[] listFiles()
Method
List all of the specified directories File object
public boolean mkdir()
Method
Create directory
public boolean renameTo(File dest)
Method
Rename the existing file
1.2 The basic operation of the file
1.2.1 Three basic operations for creating files
File file = new File("D:/AAA");
file.mkdir();// Create directory
/* Three ways to create */
// The first one is
File file01 = new File("D:\\AAA\\aaa.txt");
file01.createNewFile();// create a file
/*
\\ Directory level stay window The lower level separator of the system is \ But in linux and mac The separator on the system is /
We have to java Code is a cross platform language . We have to develop in window But our project has to be deployed in linux.
We make our code usable on any system . We have two solutions */
// The second kind ( The first solution )---- because window compatible / and \
File file02 = new File("D:/AAA/bbb.txt");
file02.createNewFile();
// The third kind of ( The second solution )----File.separator The corresponding delimiter is automatically obtained according to the system where the current code is located
File file03 = new File("D:"+File.separator+"AAA"+File.separator+"ccc.txt");
file03.createNewFile();// create a file
File file04 = new File("D:/AAA/CCC/DDD");
file04.mkdirs();// Create multi-level directory
1.2.2 Delete operation
/* Delete operation */
file03.delete();// Delete file
file02.deleteOnExit();// Delete after the program exits
file04.delete();// Delete empty directory When there is content, it cannot be deleted
1.2.3 Modify the operating
file01.setReadable(false);// Others cannot be read But you can read it yourself Set the permission of this file to unreadable
file02.setWritable(false);// Set that the file cannot be written
file03.setReadOnly();// Set read-only permission
file04.renameTo(new File("D:/AAA/CCC/EEE"));// rename
1.2.4 Query operation
File file = new File("D:/AAA/BBB/CCC/a.txt");
file.createNewFile();
// Get the name of the file
String name = file.getName();
System.out.println(" Name of file ====>"+name);
String parent = file.getParent();// Get the parent path
System.out.println(" Parent path ====>"+parent);
String path = file.getPath(); // Get the file path
System.out.println(" File path ====>"+path);
boolean file1 = file.isFile();// Determine whether the file object is a file type
System.out.println(file1);
boolean directory = file.isDirectory();// Determine whether the file object is a directory
System.out.println(directory);
File file2 = new File("D:/AAA");
String[] list = file2.list();// List AAA Names of all sub files in the directory
System.out.println(Arrays.toString(list));
1.2.5 File traversal
File[] files = file2.listFiles();
for (File f:files){
System.out.println(f);
}
1.2.6 File recursive traversal ( classic )
public static void main(String[] args) {
String path = "D:/BBB";
showAllFiles(path);
}
public static void showAllFiles(String path){
File file = new File(path);
// Determine whether the file exists or is a directory
if(!(file.exists())||!(file.isDirectory())){
return; // Exit of procedure Exit only when it does not exist or is not a directory If it is a directory, continue to call recursively ( Exit if it is a file )
}
File[] files = file.listFiles(); // List all file objects
int c = 0;
for (File f:files){
if(f.isDirectory()){
showAllFiles(f.getPath());
}else{
c++;
System.out.println(" file "+c+" by :"+f.getName());
}
}
}
2.IO flow
2.1IO The use of data streams
flow : Flow ( There is a direction , There are basic constituent units : Water drop ), Traffic ( There is a direction , Basic unit : vehicle )
Data flow : Data flow is formed by transmitting in a specific direction in bytes or characters .
2.1.1 Character output stream
// Character output stream --- Specify which file ( route ) Write operation
//true: Indicates that content is allowed to be appended to the file
FileWriter fileWriter = new FileWriter("D:/AAA/aaa.txt");
String str = " Hello world !";
fileWriter.write(str);
fileWriter.flush();// Refresh stream
fileWriter.close();// Closed flow
2.1.2 Character input stream
// This way is to read only one character at a time
// Create character input stream object . effect : It's reading aaaa.txt Contents of Li
Reader reader = new FileReader("D:/AAA/aaa.txt");
/*int read = reader.read();
System.out.println((char)read);// Read the first character
int read1 = reader.read();
System.out.println((char)read1);// Read the second character */
int r=0;
/* Cycle through all characters */
while ((r = reader.read())!=-1){
System.out.print((char)r);
}
}
// But this efficiency will be slow Because only one character is read at a time .
// We can use the character array to read several characters at a time
char[] chars = new char[10];// Custom array length
int c = reader.read(chars);// The two characters read each time are stored in the array and the number of reads is returned
String s = new String(chars, 0, c);// Convert the read array into a string
System.out.println(s);
// Then you can cycle through and read all the characters
// You can read all the characters circularly When the data cannot be read, this time c==-1, Program exit
char[] chars = new char[10];
int readC=0;// Record the number of read characters
while ((readC=reader.read(chars))!=-1){
String s = new String(chars, 0, readC);
System.out.print(s);
}
2.1.3 Use the character stream to copy the contents of the file
【 The code here uses junit Write the test unit ( Easy to write )】
requirement : take D:/AAA/aaa.txt Copy the contents of to D:/BBB/b.txt
@Test
public void test1() throws Exception {
// Create a character input stream
FileReader fr = new FileReader("D:/AAA/aaa.txt");
// Create a character output stream
FileWriter fw = new FileWriter("D:/BBB/b.txt");
int c=0;// Number of read characters
char[] chars = new char[10];// Save the data
/* When the content is not read, it returns -1*/
while ((c=fr.read(chars))!=-1){
fw.write(chars,0,c); // Write about D:/BBB/b.txt in
fw.flush();
}
fr.close();
fw.close();
}
notes : But the character stream above can't operate on pictures, movies or compressed files . Because the movie 、 music 、 Picture isochronous binary , The character stream can only operate on text .
2.2.1 Byte output stream (OutputStream)
OutputStream You can operate on any file , Output the file . In bytes . It is the parent of all byte output streams ,
// Write data to a file
@Test
public void outPutStreamTest() throws IOException {
FileOutputStream fos = new FileOutputStream("D:/AAA/aaa.txt");
String str=" Life is simple , After today is tomorrow ";
byte[] bytes = str.getBytes();// Convert string to array
fos.write(bytes);// write in
fos.close();// close resource
}
2.2.2 Byte input stream (InputStream)
It can read any file , In bytes , It is the parent of all byte input streams , Subclasses have FileInputStream
// Read one at a time
@Test
// The input stream must exist in a file Otherwise you cannot read
public void inPutStreamTest() throws IOException{
InputStream fis = new FileInputStream("D:/AAA/aaa.txt");
byte[] bytes = new byte[3];
int c=0;// Record the number of reads
// Read the data for the first time
c = fis.read(bytes); // Store the read content in byte Array
System.out.println(bytes+"=====> Number of first reads :"+c);
//d Read the data for the second time
c = fis.read(bytes); // Store the read content in byte Array
System.out.print(bytes+"=====> The number of the second reading :"+c);
}
// Read all
@Test
// The input stream must exist in a file Otherwise you cannot read
// If the content in the file is very large Use a loop to read
public void inPutStreamTestMore() throws IOException{
InputStream fis = new FileInputStream("D:/AAA/aaa.txt");
byte[] bytes = new byte[3];// The size of the array depends on the actual demand variable
int c=0;// Record the number of reads
while ((c=fis.read(bytes))!=-1){
// take byte Array to string
String s = new String(bytes, 0, c);
System.out.print(s);
}
fis.close();// close resource
}
2.2.3 Use byte input stream and output stream to copy files
explain :InputStream and OutputStream Binary and character files can be copied ( The universal )
// Copy the picture ( Text can also change the path Take the picture for example )
@Test
public void fileCopyTest() throws IOException{
//1. Create input stream
FileInputStream fis = new FileInputStream("D:/AAA/1.jpg");
//2. Create output stream
FileOutputStream fos = new FileOutputStream("D:/BBB/2.jpg");
//3. Define an array Save read content Any length
byte[] bytes = new byte[20];
int c=0;// Record the number of read contents
//4. Copy content
while ((c=fis.read(bytes))!=-1){
//5. Write the contents saved in the array to the output stream
fos.write(bytes,0,c);
}
fis.close();
fos.close();
}
2.2.4 Buffer flow
The buffer stream is in the basic stream [InputStream OutputStream Reader Writer] above Added a cache pool function can .
BufferInutStream BufferOutputStream BufferReader BufferWriter Improve IO The efficiency of , Reduce IO The number of times .
@Test
public void BufferTest() throws IOException {
OutputStream os = new FileOutputStream("D:/AAA/e.txt");
BufferedOutputStream bf = new BufferedOutputStream(os);// Buffer flow should act on basic flow
String s="aaaaa";
byte[] bytes = s.getBytes();
bf.write(bytes);// The written things are temporarily put into the cache pool , Not directly put into the file , So the file has no content
//bf.flush();// When refreshing, it will display But this one can also be skipped Because there will be an automatic refresh operation when closing the stream ( That is, refresh first and then close the stream )
bf.close();// close ---> Refresh the cache pool first and then close the resource
}
@Test
public void BufferInputTest() throws IOException{
FileInputStream fis = new FileInputStream("D:/AAA/e.txt");
BufferedInputStream bf = new BufferedInputStream(fis);
byte[] bytes = new byte[2];
int read = bf.read(bytes);
String s = new String(bytes, 0, read);
System.out.println(s);
bf.close();
}
2.2.4 Object flow
Why do I need object flow ?
We now operate IO When it's flowing , Both are string read and write operations , Can you put java Objects are read and written in files ?
Tolerable Student st=new Student(); take java Object for read and write operations The point is to persist information for example : Game archive . Because when it's running All data is in the running memory Persistence The data in memory will be run Save to hard disk The archive ( Write ) Reading ( read )
//public ObjectOutputStream(OutputStream out) throws IOException
@Test // The archive :---- serialize :
public void testObjectStream() throws Exception{
OutputStream out=new FileOutputStream("D:/AAA/a.txt");
// Object output stream
ObjectOutputStream oos=new ObjectOutputStream(out);
// Use the object output stream to call the output method Output class object This class must implement Serializable Serialization interface
Role r=new Role(" Lyu3 bu4 ","7 level ",1," Patricide ");
oos.writeObject(r);
oos.close();
}
// test Reading : ---- Deserialization :
@Test
public void testObjectStream2()throws Exception{
InputStream input=new FileInputStream("D:/AAA/a.txt");
ObjectInputStream ois=new ObjectInputStream(input);
Object o = ois.readObject();
System.out.println(o);
ois.close();
}
1. Copy the file through the character stream ----> It can only copy text files
2. Byte stream :--- Byte input stream and byte output stream .
3. Byte stream We can also copy files --- It can copy any type of file .
4. Cache stream ---> It is based on the basic flow Added a cache pool
5. Object flow : ObjectInputStream ObjectOutputStream
6. serialize : Put... In memory java Objects are stored on disk [ Network disk ] The process of .
---java The class to which the object belongs must implement the serialization interface .implements Serializable
7. Deserialization : Read the contents of the disk to java Process in object memory .
边栏推荐
- Solution: read the files with different names in the two folders and deal with the files with different mappings
- Acticiti中startProcessInstanceByKey方法在variable表中的如何存储
- 写代码涉及到的斜杠/和反斜杠\
- "Photoshop2021 tutorial" adjust the picture to different aspect ratio
- Interface and abstract class / method learning demo
- 抽卡程序模拟
- 1、 MySQL Foundation
- 项目对接支付宝支付,内网穿透实现监听支付宝的支付成功异步回调通知
- Hiding skills of Photoshop clipping tool
- 【Acwing】第61场周赛 题解
猜你喜欢

Detailed description of polymorphism

The project connects with Alipay payment, and the intranet penetration realizes the monitoring of asynchronous callback notification of successful payment of Alipay

Replication of df-gan experiment -- detailed steps of replication of dfgan and forwarding from remote port to local port using mobaxtem

Laozi cloud and Fuxin Kunpeng achieved a major breakthrough in 3D ofd 3D format documents for the first time

"Photoshop2021 tutorial" align and distribute to make dot patterns

Li Kou achieved the second largest result

再一个技巧,每月稳赚3万+

Error: cannot read properties of undefined (reading 'then')

OFDM 16 lecture 2-ofdm and the DFT

【搜索】—— 多源BFS + 最小步数模型
随机推荐
树莓派rtmp推流本地摄像头图像
使用mq消息队列来进行下单流程的高并发设计,消息挤压,消息丢失,消息重复的产生场景和解决方案
JVM上篇:内存与垃圾回收篇十四--垃圾回收器
微淼联合创始人孙延芳:以合规为第一要义,做财商教育“正规军”
支付流程如何测试?
【牛客讨论区】第七章:构建安全高效的企业服务
【搜索】Flood Fill 和 最短路模型
标准对话框 QMessageBox
[search] flood fill and shortest path model
What if Photoshop prompts that the temporary storage disk is full? How to solve the problem that PS temporary storage disk is full?
Differences among left join, inner join and right join
Acticiti中startProcessInstanceByKey方法在variable表中的如何存储
Demo of throttling function -- regular expression matching
Review of various historical versions of Photoshop and system requirements
动态内存函数的介绍(malloc free calloc realloc)
集合框架的使用
一道数学题,让芯片巨头亏了5亿美金
When using Photoshop, the prompt "script error -50 general Photoshop error appears“
树莓派输出PWM波驱动舵机
DBUtils