当前位置:网站首页>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 .
边栏推荐
- Replication of df-gan experiment -- detailed steps of replication of dfgan and forwarding from remote port to local port using mobaxtem
- [search] - multi source BFS + minimum step model
- Explanation of index failure principle and its common situations
- 抽卡程序模拟
- Event
- 安装Pygame
- What is the future development direction of software testing engineers?
- Deep Qt5 signal slot new syntax
- 集成开发环境Pycharm的安装及模板设置
- TypeScript 详解
猜你喜欢

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

对话框简介

Install pyGame

TypeScript 详解

老子云携手福昕鲲鹏,首次实现3D OFD三维版式文档的重大突破

Approval of meeting OA

How to import PS style? Photoshop style import tutorial

How do I reset Photoshop preferences? PS method of resetting preferences

二叉搜索树详讲

Idea 如何新建一个groovy的项目(图文详细解释)
随机推荐
Acceptance and neglect of events
文件处理(IO)
How to create an applet project
What about PS too laggy? A few steps to help you solve the problem
Hiding skills of Photoshop clipping tool
[Niuke discussion area] Chapter 7: building safe and efficient enterprise services
事件总结-常用总结
There is no need to install CUDA and cudnn manually. You can install tensorflow GPU through a one-line program. Take tensorflow gpu2.0.0, cuda10.0, cudnn7.6.5 as examples
Affine transformation module and conditional batch Standardization (CBN) of detailed text generated images
2022 T2i text generated image Chinese Journal Paper quick view-1 (ecagan: text generated image method based on channel attention mechanism +cae-gan: text generated image technology based on transforme
C language address book management system (linked list, segmented storage of mobile phone numbers, TXT file access, complete source code)
Approval of meeting OA
Sunyanfang, co-founder of WeiMiao: take compliance as the first essence and become the "regular army" of financial and business education
一道数学题,让芯片巨头亏了5亿美金
35.滚动 scroll
[search] connectivity model of DFS + search order
Counting Nodes in a Binary Search Tree
[search] - multi source BFS + minimum step model
Tcp server是如何一个端口处理多个客户端连接的(一对一还是一对多)
Plato farm is expected to further expand its ecosystem through elephant swap