当前位置:网站首页>Day22(File,DiGui,FileOutputStream)
Day22(File,DiGui,FileOutputStream)
2022-06-25 05:39:00 【Liuhaohao yyds】
One 、FileDemo1
package com.shujia.lhw.day22;
import java.io.File;
/*
We want to achieve IO operation , You must know the form of files on the hard disk
java Provides a class that allows us to manipulate files on the hard disk :File
File That is, the form of document expression
File: Files and directories ( Folder ) Abstract representation of pathname
Construction method :
public File(String pathname)
Create a new... By converting the given pathname string to an abstract pathname File example , If the given string is an empty string , The result is an empty abstract pathname
public File(String parent,String child)
Create a new... From the parent pathname string and the child pathname string File example
public File(File parent,String child)
Create a new... From the parent abstract pathname and child pathname strings File example
*/
public class FileDemo1 {
public static void main(String[] args) {
//public File(String pathname) Get a from a path File object
//D:\a.txt Encapsulate into a File object
File file = new File("D:\\a.txt");
System.out.println(file);
//public File(String parent,String child)
// The path of the parent :D:\demo
// The path of the child :b.txt
File file1 = new File("D:\\demo","b.txt");
System.out.println(file1);
//public File(File parent,String child)
// The path of the parent :D:\demo
// The path of the word :b.txt
File file2 = new File("D:\\demo");
File file3 = new File(file2,"b.txt");
System.out.println(file3);
}
}
---------------------------------------------------------------------------------------------------------------------------------
Two 、FileDemo2
package com.shujia.lhw.day22;
import java.io.File;
import java.io.IOException;
/*
Create features :
public boolean createNewFile()
public boolean mkdir()
public boolean mkdirs()
*/
public class FileDemo2 {
public static void main(String[] args) {
// demand : I want to D Create a folder under the disk demo2
// Encapsulated into File object , Whether the file or directory already exists is not required , He just uses a path abstractly File Express
// In the future, you can use File Some methods in class , To create or delete
File file = new File("D:\\demo2");
//public boolean mkdir() Create a directory named after this abstract path , If the destination folder already exists , We won't create , return false
System.out.println(file.mkdir());
//public boolean createNewFile() If and only if a file with that name does not already exist , Atomically create a new empty file named after the abstract pathname
try {
System.out.println(file.createNewFile());
} catch (IOException e) {
e.printStackTrace();
}
// demand 2: I want to D Under the plate demo2 Create a file in the folder b.txt
// Encapsulate the target file into File object
File file1 = new File("D:\\demo2\\b.txt");
// try {
// System.out.println(file1.createNewFile());
// } catch (IOException e) {
// e.printStackTrace();
// }
// System.out.println(file1.mkdir());
//public boolean mkdirs() Create multi-level folders
File file2 = new File("D:\\demo2\\demo3\\demo4\\demo5");
System.out.println(file2.mkdirs());
// Be careful 1: Want to create a file in a directory , The premise is that the directory must exist !!!
File file3 = new File("D:\\demo3\\b.txt");
try {
System.out.println(file3.createNewFile());// The system could not find the specified path
} catch (IOException e) {
e.printStackTrace();
}
// Be careful 2: In the future, you should find out whether you want to create files or folders , It's not necessarily the prince who rides the White Horse , There may also be Tang Monk
}
}
---------------------------------------------------------------------------------------------------------------------------------
3、 ... and 、FileDemo3
package com.shujia.lhw.day22;
import java.io.File;
import java.io.IOException;
/*
Delete function :
public boolean delete()
*/
public class FileDemo3 {
public static void main(String[] args) throws IOException {
File file = new File("D:\\a.txt");
System.out.println(file.delete());
File file1 = new File("a.txt");
System.out.println(file1.createNewFile());
File file2 = new File("aaa\\bbb\\ccc");
System.out.println(file2.mkdirs());
System.out.println(file2.delete());
File file4 = new File("aaa\\bbb");
System.out.println(file4.delete());
// demand : I want to delete aaa This folder
// Be careful : The directory to be deleted must be empty
File file3 = new File("aaa");
System.out.println(file3.delete());
}
}
--------------------------------------------------------------------------------------------------------------------------------
Four 、FileDemo4
package com.shujia.lhw.day22;
import java.io.File;
/*
Rename function :
public boolean renameTo(File dest)
*/
public class FileDemo4 {
public static void main(String[] args) {
File file = new File("D:\\ftm.jpg");
// Now I want to rename it von Timo .jpg
File file1 = new File("D:\\ Feng Timo .jpg");
System.out.println(file.renameTo(file1));
}
}
--------------------------------------------------------------------------------------------------------------------------------
5、 ... and 、FileDemo5
package com.shujia.lhw.day22;
import java.io.File;
import java.sql.SQLOutput;
/*
Judgment function :
public boolean isDirectory()
public boolean isFile()
public boolean exists()
public boolean canRead()
public boolean canWrite()
public boolean isHidden()
*/
public class FileDemo5 {
public static void main(String[] args) {
File file = new File("a.txt");
// File file = new File("b.txt");
//public boolean isDirectory() Determine whether it is a folder
System.out.println(file.isDirectory());
//public boolean isFile() Determine if it's a document
System.out.println(file.isFile());
//public boolean exits() Determine whether the target file or folder exists
System.out.println(file.exists());
//public boolean canRead() Judge whether it is readable
System.out.println(file.canRead());
//public boolean canWrite() Judge whether it is writable
System.out.println(file.canWrite());
//public boolean isHidden() Determine whether to hide
System.out.println(file.isHidden());
}
}
---------------------------------------------------------------------------------------------------------------------------
6、 ... and 、FileDemo6
package com.shujia.lhw.day22;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
Basic acquisition function :
public String getAbsolutePath()
public String getPath()
public String getName()
public long length()
public long lastModified()
*/
public class FileDemo6 {
public static void main(String[] args) {
File file = new File("a.txt");
//public String getAbsolutePath() Get absolute path , Or full path
System.out.println(file.getAbsolutePath());
//public String getName() Get the name
System.out.println(file.getName());
//public long length() The length obtained is the number of bytes
System.out.println(file.length());
//public long lastModified() What is returned is a timestamp , Accurate to milliseconds
System.out.println(file.lastModified());
//java Convert timestamp to date
//Date(long date)
// Allocate one Date object , And initialize it to indicate that it calls itself " Time " The specified number of milliseconds after the standard base time of , namely 1970 year 1 month 1 Japan 00:00:00 GMT
Date date = new Date(file.lastModified());
System.out.println(date);
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-ddHH:mm:ss");
String format = sdf.format(date);
System.out.println(format);
}
}
--------------------------------------------------------------------------------------------------------------------------
7、 ... and 、FileDemo7
package com.shujia.lhw.day22;
import java.io.File;
/*
Advanced access
public String[] list()
public File[] listFiles()
*/
public class FileDemo7 {
public static void main(String[] args) {
File file = new File("D:\\ Digital plus Technology \\ 15th issue ");
//public String[] list() Gets an array of names of all files and folders in the specified directory
String[] list = file.list();
for(String s : list){
System.out.println(s);
}
System.out.println("=======================================");
//public File[] listFile() Get all the files and folders in the specified directory File An array of objects
File[] files = file.listFiles();
for(File f : files){
System.out.println(f);
}
}
}
---------------------------------------------------------------------------------------------------------------------------------
8、 ... and 、FileDemo8
package com.shujia.lhw.day22;
import java.io.File;
/*
Demand analysis : Judge D Is there... Under the plate .jpg Later documents , If there is , Just output the file name
1、 take D The root directory is encapsulated into a File object
2、 Get all the files or folders in the directory File An array of objects
3、 Traverse File Array , Get every one File object , And then determine if it's a file
yes : Continue to judge whether to use .jpg suffix
yes : Output name
No : Regardless of him
No : Regardless of him
*/
public class FileDemo8 {
public static void main(String[] args) {
File file = new File("D:\\");
File[] files = file.listFiles();
for(File f : files){
if(f.isFile()){
if (f.getName().endsWith(".jpg")){
System.out.println(f.getName());
}
}
}
}
}
-------------------------------------------------------------------------------------------------------------------------------
Nine 、FileDemo9
package com.shujia.lhw.day22;
import java.io.File;
import java.io.FilenameFilter;
/*
First judge D Is there... Under the plate .jpg Later documents , Output the file name if any
1、 Get all the files and folders first , Then when traversing , Then judge whether it is a file , Whether it is .jpg Suffix , Finally, filter out the files that meet the conditions to obtain the name ,
2、 At the time of acquisition , The data obtained meets the conditions , We can output it directly
Implementation idea and code of file name filter
public String[] list(FilenameFilter filter)
public File[] listFile(FilenameFilter filter)
*/
public class FileDemo9 {
public static void main(String[] args) {
// establish File object
File file = new File("D:\\");
//public String[] list(FilenameFilter filter)
String[] list = file.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
// return false;
// return true;
// Found by test , Should the files or folders in the directory be obtained , Depending on the return value here
//true, Get the array , If it is false, Don't get , Not added to the array
// System.out.println(dir);
// System.out.println(name);
File file1 = new File(dir,name);
boolean b = file.isFile();
boolean b1 = name.endsWith(".jpg");
return b && b1;
}
});
for (String s : list){
System.out.println(s);
}
}
}
-----------------------------------------------------------------------------------------------------------------------------
Ten 、DiGuiDemo1
package com.shujia.lhw.day22;
/*
recursive : Method defines the phenomenon of calling method itself
Math.max(Math.max(a,b)c) This phenomenon is only the nesting of methods, not the recursive use of methods
give an example :
1、 Once upon a time there was a mountain , There is a temple in the mountain , There is an old monk in the temple , The old monk is telling a story to the little monk , The content of the story is :
Once upon a time there was a mountain , There is a temple in the mountain , There is an old monk in the temple , The old monk is telling a story to the little monk , The content of the story is :
Once upon a time there was a mountain , There is a temple in the mountain , There is an old monk in the temple , The old monk is telling a story to the little monk , The content of the story is :
...
The temple fell down , The old monk passed away
2、 Learn big data -- High paid employment -- To earn money -- Marry a daughter-in-law -- Born baby -- Earn tuition :
Learn big data -- High paid employment -- To earn money -- Marry a daughter-in-law -- Born baby -- Earn tuition :
Learn big data -- High paid employment -- To earn money -- Marry a daughter-in-law -- Born baby -- Earn tuition :
...
Can't get a daughter-in-law , Can't have a baby
Recursion considerations :
1、 Recursion must have an exit ( The end condition ), Otherwise it will be dead
2、 You can't recurse too many times , Otherwise, it will cause , Stack memory overflow
3、 Constructors cannot be recursive
*/
public class DiGuiDemo1 {
// public DiGuiDemo1(){
// new DiGuiDemo1();
// }
// Dead recursion
public void show(){
show();
}
}
-------------------------------------------------------------------------------------------------------------------------------
11、 ... and 、DiGuiDemo2
package com.shujia.lhw.day22;
/*
demand : Find out the implementation with code 5 The factorial
5!=5*4*3*2*1
=5*4!
=5*4*3!
=5*4*3*2!
=5*4*3*2*1!
1、 Solve with circulation
2、 Solve with recursion
*/
public class DiGuiDemo2 {
public static void main(String[] args) {
int i = 1;
for (int x = 2;x <= 5;x++){
i = i*x;
}
System.out.println("5 The factorial is :"+i);
// Use recursive method to realize
System.out.println("5 The factorial is :"+diGui(5));
}
/*
The premise of recursive method :
return type :int
parameter list :int i
Export conditions :if(i==1){return 1}
Recursive topic logic :
if(i!=1){
return i*deGui(i-1);
}
*/
public static int diGui(int i){
if(i==1){
return 1;
}else {
return i*diGui(i-1);
}
}
}
---------------------------------------------------------------------------------------------------------------------------------
Twelve 、DiGuiDemo3
package com.shujia.lhw.day22;
/*
Undead rabbit case :
Suppose there are a pair of Rabbits , From the third month of life , A couple of rabbits are born every month , After the third month, the rabbit grows up , Another pair of rabbits are born every month
Suppose all rabbits don't die
problem : Twenty months later , What are the logarithm of the rabbit ?
Looking for a regular :
month The number of Rabbits
First month 1
The second month 1
The third month 2
The fourth month 3
The fifth month 5
The sixth month 8
...
thus it can be seen , The logarithm of the rabbit is :
1,1,2,3,5,8,13,21,34...
law :
1、 Start with the third item , Each is the sum of the first two
2、 Explain that the data of the first two items are known
How to achieve it ?
1、 Array implementation
2、 Basic variable implementation
3、 Recursive implementation
Define two variables as adjacent data
The first 1 Adjacent data :a=1,b=1
The first 2 Adjacent data :a=1,b=2
The first 3 Adjacent data :a=2,b=3
The first 4 Adjacent data :a=3,b=5
law : Next adjacent data ,a The value of is the last time b Value ,b The value of is the sum of the last adjacent data a+b
*/
public class DiGuiDemo3 {
public static void main(String[] args) {
// Implementation with array
int[] arr = new int[20];
arr[0] = 1;
arr[1] = 1;
// arr[2] = arr[0] + arr[1];
// arr[3] = arr[1] + arr[2];
// //...
// arr[19] = arr[17] + arr[18];
for(int i = 2;i<arr.length;i++){
arr[i] = arr[i-2] + arr[i-1];
}
System.out.println(" The first 20 The number of rabbits after months is :"+arr[19]);
System.out.println("=============================================");
// Basic variable implementation
// Next adjacent data ,a The value of is the last time b Value ,b The value of is the sum of the last adjacent data a+b
int a = 1;
int b = 1;
for(int i = 1;i <= 18;i++){
// Define a temporary variable , Store the last time a Value
int tmp = a;
a = b;
b = tmp + b;
}
System.out.println(" The number of rabbits after the 20th month is :"+b);
System.out.println("=============================================");
// Recursive form
System.out.println(" The number of rabbits after the twentieth month is :"+Fibonacci(20));
}
/*
return type :int
parameter list :int i 20
<p>
Export conditions : The first month was 1, The second month is also 1
The condition of recursion : From the third month on , The value of each month is the sum of the first two months
*/
public static int Fibonacci(int i){//4
// The first month was 1, The second month is also 1
if(i ==1 | i == 2){
return 1;
}else {
// From the third month on , The value of each month is the sum of the previous two months
return Fibonacci(i-1) + Fibonacci(i-2);
//Fibonacci(3) + Fibonacci(2)
//Fibonacci(2) + Fibonacci(1) + 1
//1 + 1 + 1
//3
}
}
}
---------------------------------------------------------------------------------------------------------------------------------
13、 ... and 、DiGuiDemo4
package com.shujia.lhw.day22;
import java.io.File;
/*
Traverse all the file names with the specified suffix in the specified directory D:\ Digital plus Technology \ 15th issue
analysis :
1、 Encapsulate the directory into File object
2、 Get all under this directory File An array of objects
3、 Traverse the array to get each File object
4、 The result of judgment File Is the object a file or a folder
1) If it's a folder , Go back to step two
2) If he is a file , Judge whether the file name is marked with .java suffix
If it is , Output
If not , skip
*/
public class DiGuiDemo4 {
public static void main(String[] args) {
// Encapsulate the directory into File object
File file = new File("D:\\ Shujia College \\ 15th issue ");
// Recursive implementation
getJavaFile(file);
}
public static void getJavaFile(File file){
// Get all under this directory File An array of objects
File[] files = file.listFiles();
// Traverse the array to get each File object
for (File f : files){
// Decide if it's a folder
if (f.isDirectory()){
getJavaFile(f);
}else{
// Judge whether the file name is marked with .java suffix
if (f.getName().endsWith(".java")){
// If it is , Output
System.out.println(f.getName());
}
}
}
}
}
------------------------------------------------------------------------------------------------------------------------------
fourteen 、DiGuiDemo5
package com.shujia.lhw.day22;
import java.io.File;
/*
Recursively delete directory with content :
analysis :
1、 obtain File object
2、 Get all the files and folders in the directory File An array of objects
3、 Traverse the array to get each File object
4、 Judge this File Whether the object is a folder
yes : Go back to step two
No : Delete directly
*/
public class DiGuiDemo5 {
public static void main(String[] args) {
File file = new File("D:\\IdeaProjects\\bigdata15\\aaa");
deleteFile(file);
}
public static void deleteFile(File file){
// Get all the files and folders in the directory File An array of objects
File[] files = file.listFiles();
if(files!=null){
// Traverse the array to get each File object
for (File f : files){
// Judge this File Whether the object is a folder
if(f.isDirectory()){
deleteFile(f);
}else{
System.out.println(f.getName()+"---"+f.delete());
}
}
System.out.println(file.getName()+"---"+file.delete());
}
}
}
-------------------------------------------------------------------------------------------------------------------------------
15、 ... and 、FileOutputStreamDemo1
package com.shujia.lhw.day22;
import java.io.File;
import java.io.FileOutputStream;
/*
IO Classification of flows :
flow :
Input stream Reading data
Output stream Writing data
data type :
Byte stream
Byte input stream Reading data InputStream
Byte output stream Writing data OutputStream
Character stream
Character input stream Reading data Reader
Character output stream Writing data Writer
demand : Go to a.txt Write a sentence in the file :" big data ,yyds"
analysis :
1、 Because it operates on text files , It's best to use character stream to do , But today we will focus on byte stream , Character stream is based on byte stream , Now it is realized by throttling
2、 We're going to write a sentence to the file , You need to use the output stream , Here is the byte output stream
Through the above analysis , Final lock OutputStream
Observe API After the discovery ,OutputStream Is an abstract class , Can't be instantiated directly
FileOutputStream:
Construction method :
FileOutputStream(File file) Create a file output stream to write to the specified File File represented by object
FileOutputStream(String name) Create a file output stream to write to the file with the specified name
Steps of byte output stream :
1、 Create byte output stream object
2、 Calling method , Writing data
3、 Release resources
*/
public class FileOutputStreamDemo1 {
public static void main(String[] args) throws Exception{
// Create a byte stream output object
//FileOutputStream(File file) Creates a file output stream to write to the File File represented by object
File file = new File("b.txt");
// If the target file does not exist , Automatically create
// FileOutputStream fos = new FileOutputStream(file);
//FileOutputStream(String name) Create a file output stream to write to the file with the specified name
// If the target file does not exist , Automatically create
FileOutputStream fos = new FileOutputStream("c.txt");
// System.out.println(fos);
// Calling method , Writing data
fos.write(" big data ,yyds".getBytes());
// Release resources
//close() Close this file output stream and free any system resources associated with this stream
fos.close();
fos.write(" Continue writing ".getBytes());
}
}
-------------------------------------------------------------------------------------------------------------------------------
sixteen 、FileOutputStreamDemo2
package com.shujia.lhw.day22;
import java.io.FileOutputStream;
/*
Several methods of writing data in byte output stream :
public void write(int b)
public void write(byte[] b)
public void write(byte[] b,int off,int len)
*/
public class FileOutputStreamDemo2 {
public static void main(String[] args) throws Exception{
// Create byte output stream object
FileOutputStream fos = new FileOutputStream("d.txt");
//public void write(int b)
//97, The binary stored at the bottom ,97 Corresponding ASCII The character of the code is a
fos.write(97);
fos.write(48);
fos.write(65);
//public void write(byte[] b)
byte[] bytes = {97,98,99,100,101};
fos.write(bytes);
//public void write(byte[] b,int off,int len)
// From at offset off Writes the specified byte array of len Bytes to the file output stream
fos.write(bytes,1,3);
// Release resources
fos.close();
}
}
------------------------------------------------------------------------------------------------------------------------------
seventeen 、FileOutputStreamDemo3
package com.shujia.lhw.day22;
import java.io.FileOutputStream;
/*
1、 How to realize line feed ?
Want to know why there is no line feed ? Because we only write bytes of data , No newline is written
How to achieve it ? At the writing Festival , Add a line break , Be careful : Different systems , Line breaks are not necessarily the same
Mac:\r
Windows:\r\n
Linux:\n
2、 How to implement addition ?
*/
public class FileOutputStreamDemo3 {
public static void main(String[] args) throws Exception {
// Create byte output stream object
// FileOutputStream fos = new FileOutputStream("e.txt");
// fos.write(" big data 1,yyds".getBytes());
// fos.write("\r\n".getBytes());
// fos.write(" big data 2,yyds".getBytes());
//FileOutputStream(String name,boolean append)
// Create a file output stream to write to the file with the specified name
//true It means that data can be added and written
FileOutputStream fos = new FileOutputStream("e.txt", true);
fos.write("\r\n it's snowing today \r\n".getBytes());
// fos.write("\r\n".getBytes());
fos.write(" But I didn't see the snow ".getBytes());
// Release resources
fos.close();
//...
}
}
边栏推荐
- 钱堂教育的证券账户安全吗?靠谱吗?
- Two dimensional array and function call cases of C language
- Object creation and invocation code example
- MySQL prevents Chinese garbled code and solves the problem of Chinese garbled code
- Use of MySQL variables
- A brief talk on media inquiry
- 投资理财产品的年限要如何选?
- Extend the toolbar of quill editor
- Edge loss 解读
- Critical dependency: require function is used in a way in which dependencies
猜你喜欢

Multithreading and thread pool

DOM document object model (I)
Learn the interface test, see it is very good, and make a note

Detailed summary of position positioning

Stack and Queue

In depth understanding of line height and vertical align
![[day40 literature extensive reading] space and time in the child's mind: metallic or atomic](/img/98/10b3e63c9609990c51b619d9ca6179.jpg)
[day40 literature extensive reading] space and time in the child's mind: metallic or atomic

JSON Library Tutorial from scratch (III): parsing strings, learning and sorting notes

Voxel based and second network learning

2022.1.25
随机推荐
Monkey test of APP automation
Read the general components of antd source code
Go Basics
"APEC industry +" biov Tech talks about the cross-border of Chinese biotechnology enterprises and "Pratt & Whitney Kangyu" | apec-hub public welfare
H5 native player [learn video]
CopyPlugin Invalid Options options should be array ValidationError: CopyPlugin Invalid Options
About the definition of pointer variables (personal notes)
What happens when you use "-fno exceptions", "new T"- With “-fno-exceptions”, what happens with “new T”?
Keyboard key code value
JS handwriting depth clone array and object
Tanhaoqiang C language practice
Vue uses keep alive to cache page optimization projects
JS verification code input number auto skip
First blog
Jenkins installation and configuration
[relax's law of life lying on the square] those poisonous chicken soup that seem to be too light and too heavy, but think carefully and fear
MySQL operation JSON
Unsupervised domain adaptation in semantic segmentation:a review unsupervised domain adaptation in semantic segmentation: a review
How do product managers get started? How do they learn when no one takes them?
Multithreading and thread pool