当前位置:网站首页>IO should know and should know
IO should know and should know
2022-07-23 11:01:00 【Xiaopucai learns Java】
Catalog
Hardware architecture : processor CPU, Memory ( Memory ), input device , Output devices
Comparison of reading and writing speed of various hardware
File path : From the file system tree , Find the only certain location , This node may not exist .
Reading and writing of documents
Read data of file :FileInputStream
simulation OJ Writing of test documents
Hardware architecture : processor CPU, Memory ( Memory ), input device , Output devices
Hard disk —— Storage :

Comparison of reading and writing speed of various hardware

File path : From the file system tree , Find the only certain location , This node may not exist .
Absolute path : Start from the root node of the file tree , Find the node location of a file , It's the absolute path
Relative paths : Start from the current file node , The position of the other node relative to the current node
. .: Go back to the next level
. : Represents the current directory
Current directory : The process has to start the directory ,
Path description :
Absolute path :\ : Path separator
window:D:\ files \ a.txt Root drive letter : \ file name \ file . Suffix name
linux:/ mac: D: / Folder / file name
Relative paths : Directory when the process starts
public class Relative paths {
public static void main(String[] args) throws IOException {
File file = new File("./a.txt");
System.out.println(file.getCanonicalPath());
}
}The current in file Folder : describe a.txt for : file\a.txt
Path in code : windows in \ To signify an escape , therefore windows Code in : D:\\file\\a.txt
java Is a cross platform language , So the code can not distinguish between forward and backward slashes
File class :
Construction method

Common method :



Delete file delete()
Only leaf nodes or empty folders can be deleted ;
deleteOnExit() : Delete files when program exits ;
Delete non empty folder , You can only delete the folder as empty , To delete the folder
Document creation and judgment
windows Deleting files on is equivalent to cutting and copying , Copy files from the current node to the recycle bin ,
delete() The method is to delete the real file system , Don't go into the recycle bin
package com.yyk.io.IO Operation file ;
import java.io.File;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Date;
import java.util.Deque;
public class FileMetohd {
public static void main(String[] args) throws IOException {
File file = new File("D:\\IO\\.\\..\\..\\IO\\hello.txt");
System.out.println(" Does the file exist :"+file.exists());
System.out.println(" Is it a folder :"+file.isDirectory());
System.out.println(" Is it a document " + file.isFile());
System.out.println("*********** Create... Under this path hello.txt*******");
file.createNewFile();
System.out.println(" Does the file exist :"+file.exists());
System.out.println(" Is it a folder :"+file.isDirectory());
System.out.println(" Is it a document " + file.isFile());
System.out.println();
System.out.println("******** Get the path of the file **********");
System.out.println(" The absolute path of the file :" +file.getAbsoluteFile());// The returned file
System.out.println(" The absolute path of the file :" +file.getAbsolutePath());// Return a string
System.out.println(" The authoritative absolute path of the file :" +file.getCanonicalFile());// The returned file , Remove the meaningless point in the middle
System.out.println(" The authoritative absolute path of the file :" +file.getCanonicalPath());// Return a string , Remove the middle file .. and .
System.out.println(" file name :" + file.getName());
System.out.println(" The parent path of the file :" + file.getParent());
System.out.println(" Authoritative path of the parent path of the file :" + file.getParentFile().getCanonicalPath());
System.out.println(" File size :" + file.length());
System.out.println(" Files created with absolute paths :" +file.isAbsolute());
System.out.println(" Is the file hidden :" +file.isHidden());
System.out.println(" The last time the file was modified :" + new Date(file.lastModified()));
System.out.println(" The number of files in the parent directory of the file :" + Arrays.toString(file.getParentFile().listFiles()));
System.out.println();
System.out.println("******** The depth of the file is traversed first ***********");
DFSFilePath(file.getParentFile());
System.out.println();
System.out.println("******** Breadth first traversal of files ***********");
NFSFilePath(file.getParentFile());
System.out.println(" The root directory of the file system " + file.listRoots());
System.out.println();
System.out.println("*****mkdir**** Create folder *******mkdirs****");
File file1 = new File("D:\\IO\\A\\BB\\CCC");
file1.mkdirs();
System.out.println("mkdirs Create a folder under a nonexistent path " + file1.getCanonicalPath());
File file2 = new File("D:\\IO\\D");
file2.mkdir();
System.out.println("mkdir Create a folder under an existing directory :" + file2.getCanonicalPath());
System.out.println(" Rename file :" );
File dest = new File("D:\\IO\\ Hello .txt");
System.out.print(file.getName()+" It was renamed ");
file.renameTo(dest);
dest.delete();// Delete folder
System.out.println(dest.getName());
System.out.println(" Renaming a file is equivalent to cutting and copying a file ");
}
/**
* The depth of the file is traversed first
* @param dir
*/
public static void DFSFilePath(File dir) throws IOException {
File[] files = dir.listFiles();
if (dir == null){
return;
}
for (File file: files) {
if (file.isDirectory()){
System.out.println(dir.getCanonicalPath()+" In the catalog "+file.getName()+" Folder ");
DFSFilePath(file);
}else {
System.out.println(dir.getCanonicalPath()+" In the catalog "+file.getName()+" file ");
}
}
}
/**
* File breadth first traversal
* @param dir
* @throws IOException
*/
public static void NFSFilePath(File dir) throws IOException {
Deque<File> fileDeque = new ArrayDeque<>();
fileDeque.offer(dir);
while (!fileDeque.isEmpty()){
File file = fileDeque.poll();
if (file.isDirectory()){
File[] files = file.listFiles();
for (File f:files) {
fileDeque.offer(f);
}
System.out.println(" Folder :" + file.getCanonicalPath());
}else {
System.out.println(" file :" + file.getCanonicalPath());
}
}
}
}
Reading and writing of documents
Read data of file :FileInputStream
1, Read the file in the form of byte stream
conceptual model :


2, Read files in character stream ( Text files )
Whether it's a byte stream or a character stream , It's all used Scanner Class to read data
public class Read data with Scanner {
public static void main(String[] args) throws Exception{
try(InputStream is = new FileInputStream("./hello.txt")){
try(Scanner scanner = new Scanner(is,"UTF-8")){
while (scanner.hasNextLine()){
String next = scanner.nextLine();
System.out.println(next);
}
}
}
}
}

Write OutputStream:
Write data when closing resources , You need to flush the buffer , Avoid data that has not been written in the buffer .


Copy of documents
public class File replication {
public static void main(String[] args) throws Exception {
InputStream is = new FileInputStream("D:\\IO\\12.jpg");
byte[] buff = new byte[10240];// buffer , Used to match the reading and writing speed gap between memory and hard disk
OutputStream os = new FileOutputStream("D:\\IO\\34.jpg");
while (true){
int read = is.read(buff);
if (read == -1){// If it is EOS, There is no data , immediate withdrawal
break;
}
os.write(buff);// Write all the bytes read into the buffer into the file
os.flush();// Finally, flush the buffer zone
}
}
}Copy of folder
package com.yyk.io.IO Operation file ;
import java.io.*;
public class Folder copy {
static File srcFile = new File("D:\\IO\\A");// Source directory
static File tarFile = new File("D:\\IO\\D"); // Destination file directory
public static void main(String[] args) throws Exception{
copy(srcFile);
}
private static void copy(File dirFile) throws Exception {
File[] files = dirFile.listFiles();
if (files == null){
return;
}
for (File file:files) {
String filePath = file.getCanonicalPath();// The directory of the current file
String tarFilePath = tarFile.getCanonicalPath();// The root directory of the files to be copied
String aimPath= tarFilePath + filePath.substring(srcFile.getCanonicalPath().length());// The directory that needs to be copied
File aimFile = new File(aimPath);
if (file.isDirectory()) {// If it's a folder , Create folder
aimFile.mkdir();
// Just continue to traverse
copy(file);
}else if (file.isFile()){
copyFile(file,aimFile);
}
}
}
public static void copyFile(File file,File aimFile) throws Exception {
InputStream is = new FileInputStream(file);
byte[] buff = new byte[10240];// buffer , Used to match the reading and writing speed gap between memory and hard disk
OutputStream os = new FileOutputStream(aimFile);
while (true){
int read = is.read(buff);
// System.out.println(" I read "+read+" Bytes ");
if (read == -1){// If it is EOS, There is no data , immediate withdrawal
break;
}
os.write(buff,0,read);// Write all the bytes read into the buffer into the file
os.flush();// Finally, flush the buffer zone
}
}
}
simulation OJ Writing of test documents
package com.yyk.io.IO Operation file .oj;
public class Node {
int val ;
Node next;
public Node(int val){
this.val = val;
}
}
package com.yyk.io.IO Operation file .oj;
public class Solution {
public Node reverse(Node head){
Node prev = null;
Node cur = head;
while (cur != null){
Node next = cur.next;
cur.next = prev;
prev = cur;
cur =next;
}
return prev;
}
}
package com.yyk.io.IO Operation file .oj;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;
public class Test case verification {
static Solution solution = new Solution();
static File inputFile = new File("D:\\IO\\C\\input.txt");
static File resFile = new File("D:\\IO\\C\\output.txt");
public static void main(String[] args){
try{
// Read input and output files by line
InputStream is = new FileInputStream(inputFile);// Input
InputStream res = new FileInputStream(resFile);// result
Scanner isSc = new Scanner(is,"UTF-8");
Scanner resSc = new Scanner(res,"UTF-8");
while (isSc.hasNextLine()){
String inStr = isSc.nextLine();
String resStr = resSc.nextLine();
test(inStr,resStr);
}
System.out.println(" Through all the test cases ");
}catch (Exception e){
}
}
private static void test(String inStr,String resStr){
StringBuilder sb = new StringBuilder();
try {
// take instr Press find space to separate , To int, Create a linked list and reverse
String[] strs = inStr.split(" ");
Node head = new Node(-1);
Node tem = head;
for (String s:strs) {
Node node = new Node(Integer.parseInt(s));
tem.next = node;
tem = node;
}
Node newNode = solution.reverse(head.next);// New linked list after inversion
// Traverse the linked list into a string
while (newNode != null){
sb.append(newNode.val + " ");
newNode = newNode.next;
}
// Finally, remove the last space
sb.delete(sb.length() - 1,sb.length());
if (!resStr.equals(sb.toString())){
System.out.println(" Enter the use case :" + inStr);
System.out.println(" Expected output :" + resStr);
System.out.println(" The actual output :" + sb.toString());
System.exit(1);
}
}catch (Exception e){
System.out.println(" Enter the use case :" + inStr);
System.out.println(" Expected output :" + resStr);
System.out.println(" The actual output :" + sb.toString());
e.printStackTrace();
}
}
}
边栏推荐
- PXE remote installation and kickstart unattended installation technical documents
- H1--HDMI接口测试应用2022-07-15
- R language uses DALEX package to explain and analyze the machine learning model built by H2O package: summary and Practice
- sort
- Error in na.fail. default(list(Purchase = c(“CH“, “CH“, “CH“, “MM“, “CH“, : missing values in obj
- Question 300 Leçon 6 type quadratique
- 【ROS进阶篇】第八讲 URDF文件的语法详解
- NOTIFIER诺帝菲尔消防主机电源维修及日常维护
- 软件测试基本概念篇
- C语言n番战--共用体和枚举(八)
猜你喜欢

8. Surface geometry

Dynamic memory management

Redis source code and design analysis -- 14. Database implementation

软件测试基本概念篇
![[unity daily bug] unity reports an unexpected character '‘](/img/e8/11eec670112a5a7e4f1e71dc93c1c0.png)
[unity daily bug] unity reports an unexpected character '‘

Redis源码与设计剖析 -- 7.快速列表

LearnOpenGL - Introduction

对比redis的RDB、AOF模式的优缺点

The 12th Blue Bridge Cup embedded design and development project

Two strategies for building AI products / businesses (by Andrew ng)
随机推荐
Error in na.fail.default(list(Purchase = c(“CH“, “CH“, “CH“, “MM“, “CH“, : missing values in obj
PXE remote installation and kickstart unattended installation technical documents
adb常用命令
The 12th Blue Bridge Cup embedded design and development project
Important knowledge of application layer (interview, reexamination, term end)
【社媒营销】出海新思路:Whatsapp Business替代Facebook
N wars of C language -- common body and enumeration (VIII)
Redis source code and design analysis -- 13. Ordered collection objects
Deploy storageclass trample record
Redis源码与设计剖析 -- 10.列表对象
Two strategies for building AI products / businesses (by Andrew ng)
【Swift|Bug】Xcode提示Error running playground: Failed to prepare for communication with playground
300 questions, Lecture 6, quadratic form
Redis source code and design analysis -- 11. Hash object
Meyer Burger梅耶博格西门子工控机维修及机床养护
【ROS进阶篇】第八讲 URDF文件的语法详解
Matlab中的滤波器
Recommend a shell installation force artifact, which has been open source! Netizen: really fragrant...
XSSGAME小游戏(XSS学习)level1-15
一次 MySQL 误操作导致的事故,「高可用」都不好使了