Java file operation object IO stream

await 2021-09-15 07:22:41
java file operation object io


//File object C:/Users/28528/Desktop/java File to practice
// Construct a FIle object , Incoming file path ( Absolute path , Relative paths )
// The absolute path is the full path starting with the root directory Such as C:/Users/java File to practice
// Relative paths Such as /usr/bin/javac
// Be careful Windows Platform use \ As path separator ,
// stay Java You need to use... In the string \\ It means a \.Linux Platform use / As path separator
// It can be used . Represents the current directory ,.. Indicates the parent directory .
File f1 = new File("sub\\javac"); // The absolute path is C:\Docs\sub\javac
File f2 = new File(".\\sub\\javac"); // The absolute path is C:\Docs\sub\javac
File f3 = new File("..\\sub\\javac"); // The absolute path is C:\sub\javac
File f=new File("C:/Users/28528/Desktop/java File to practice ");
File f4=new File("..");
System.out.println(f1+"\n"+f2+"\n"+f3+"\n"+f);
System.out.println(f1.getCanonicalPath());
String file=File.separator;
//File.separator Print according to the current platform "\" or "/" Static variables separator System separator
System.out.println(file);
//File There are three forms of objects 1.getPath 2.getAbsolutePath 3.getCanonicalPath
//1 Returns the path passed in by the constructor
//2 Return to absolute path
//3 Return specification path Similar to the absolute path 
//File Calling method
//1 Judge File Whether the path in the object exists
File f1=new File("C:/Users/28528/Desktop/java File to practice ");// Catalog
File f2=new File("C:\\Users\\28528\\Desktop\\demo1.txt");// file
System.out.println(f2.isFile());// Determine whether a file exists true false
System.out.println(f1.isDirectory());// Determine whether a directory exists true false
//2 obtain File Object's file permissions and size
// use File Object to get a file , You can also further determine the permissions and size of the file :
// boolean canRead(): Is it readable? ;
// boolean canWrite(): Is it possible to write ;
// boolean canExecute(): Is it executable ;
// long length(): File byte size .
System.out.println(f2.length());
//File Create and delete files
String name1=" Default folder 1",name2="txt";// The default file name is followed by the suffix
System.out.println(" Whether to customize the file name (y):");
char shu=in.next().charAt(0);
if(shu=='y'){
System.out.println(" Please enter filename :");
name1=in.next();// Enter the name of the created file
System.out.println(" Please enter the suffix :");
name2=in.next();// Enter the suffix of the created file
}
File file=new File("C:/Users/28528/Desktop/"+name1+"."+name2);
System.out.println(file);// Output file name
if(file.isFile())// Determine if there is a file
{
if(file.delete()){// There are files to delete
System.out.println(" The file has been deleted ");
}
}else{// Create a file if it doesn't exist The created file name needs to be suffixed by itself
file.createNewFile();// Create a file
System.out.println(" File created successfully ");
System.out.println(" Delete created file (y):");
shu=in.next().charAt(0);
if(shu=='y'){
if(file.delete()){
System.out.println(" File deleted ");
}
}
}

Automatically delete after running

{tabs-pane label=" Code "}

//File The temporary file
// Prefix and suffix of temporary files
File file=File.createTempFile(" This is a temporary file ",".txt");
//JVM Automatically delete on exit
file.deleteOnExit();
System.out.println(file.isFile());// Judge whether the file exists
System.out.println(file.getAbsolutePath());// Return the absolute path of the file 

{/tabs-pane} {tabs-pane label=" picture "}

{/tabs-pane}

{tabs-pane label=" Code "}

//File Get the file and subdirectory names under the directory
File file=new File("C:/Users/28528/Desktop/");
File[] filelist=file.listFiles();// Get all files and subdirectories
for(File f:filelist){// utilize foreach Loop print all files and subdirectories
System.out.println(f);
}
//FilenameFilter The live directory of files that meet the file requirements returns
File[] filelist2=file.listFiles(new FilenameFilter(){
@Override
public boolean accept(File dir,String name){
return name.endsWith(".docx");// return true Indicates that the file was received
//endsWith Filter out the specified suffix
//startsWith Filter out the specified prefix
}
});
printlnfiles(filelist2);//foreach Method of circular printing 

{/tabs-pane} {tabs-pane label="printlnfiles Method "}

public static void printlnfiles(File[] f){
System.out.println("````````````````````");
if(f!=null){
for(File file:f){
System.out.println(file);
}
}
System.out.println("````````````````````");
}

Similar to file manipulation ,File Object represents a directory , You can create and delete directories in the following ways :

boolean mkdir(): Create current File Object represents the directory ; boolean mkdirs(): Create current File Object represents the directory , And create a parent directory that doesn't exist when necessary ; boolean delete(): Delete the current File Object represents the directory , The current directory must be empty to delete successfully . {/tabs-pane} {tabs-pane label=" picture "}

{/tabs-pane}

This article altogether 700 Number of words , Average reading time ≈ 2 minute

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[await]所创,转载请带上原文链接,感谢
https://javamana.com/2021/09/20210909125824215w.html

  1. Design pattern -- agent pattern
  2. Huawei Java Senior Engineer interview question, Byte Jumping thousand Selected Interview Question is still not Brushed!
  3. 双非本科字节跳动Java面试题分享,一篇文章教你搞定计算机网络面试,
  4. 又到一年金三银四,2021最新Java笔试题及答案,
  5. Huawei Finance and Economics 2021 Spring Recruitment interview, what is distributed Lock?Pourquoi utiliser des serrures distribuées?
  6. Un an plus tard, Golden, Silver, Silver, and Silver, 2021, the latest Java written Examination Questions and Answers,
  7. Partage de questions d'entrevue Java à double saut d'octets non - premier cycle, un article vous apprend à gérer l'entrevue réseau informatique,
  8. Computer graduation project java online voting system based on SSM
  9. K8s gestion des ressources (opérations de base)
  10. 又到一年金三銀四,2021最新Java筆試題及答案,
  11. Collection de code de base JavaScript (1)
  12. Vérification des permissions d'interface pour le démarrage du printemps à l'aide d'annotations personnalisées AOP +.
  13. Vérification des permissions d'interface pour le démarrage du printemps à l'aide d'annotations personnalisées AOP +.
  14. Cloud Security Daily 210914: Red Hat Jboss Middleware Platform found important Security Vulnerability and needs to be upgraded as soon as possible
  15. 吐血整理,腾讯团队实力打造spring入门教程,
  16. 史上最全的微服务专业术语面试50问,字节跳动Java岗经典面试真题,
  17. Absolument!C'est l'analyse la plus détaillée du code source de hashtap que j'ai jamais vu!
  18. Computer graduation project Java logistics order management system of logistics company based on SSM
  19. Talk about Kafka: source code analysis of producer
  20. [springboot2 starts from 0] development tips - Lombok, devtools, spring initailizr
  21. 国内一线互联网公司面试题汇总,2021年大厂Java岗面试必问,
  22. 啃完吃透保你涨薪5K,熬夜整理小米Java面试题,
  23. 和字节跳动大佬的技术面谈,Redis成神之路电子版教程已问世,
  24. Le terme professionnel le plus complet de l'histoire des micro - services interview 50 questions, Byte Jumping Java post Classic interview vrai problème,
  25. After using mybatisplus, I haven't written SQL for a long time
  26. [springboot2 starts from 0] how to write a springboot application?
  27. Huawei cloud guassdb (for redis) released a new version, and the two core features were officially unveiled
  28. 和字節跳動大佬的技術面談,Redis成神之路電子版教程已問世,
  29. 啃完吃透保你漲薪5K,熬夜整理小米Java面試題,
  30. Avec l'interview technique du gigolo, le tutoriel électronique redis est sorti.
  31. Après avoir mangé, assurez - vous d'augmenter votre salaire de 5K et de rester debout tard pour trier les questions d'entrevue Java de millet.
  32. Résumé des questions d'entrevue pour les entreprises Internet nationales de première ligne, qui doivent être posées lors de l'entrevue d'emploi Java de la grande usine en 2021,
  33. Le tri des crachats de sang, la force de l'équipe Tencent pour créer le tutoriel d'introduction au printemps,
  34. Java and scala concurrency Fundamentals
  35. Analysis of java thread source code based on Hotspot
  36. 國內一線互聯網公司面試題匯總,2021年大廠Java崗面試必問,
  37. Introduction au module de contrôle de Connexion MySQL
  38. 大厂高级测试面试题,Java面试基础技能罗列,
  39. Comprendre l'architecture sous - jacente d'InnoDB en exécutant une instruction
  40. Chargeur de classe 1 Tomcat
  41. 小白也能看懂的dubbo3应用级服务发现详解
  42. SpringBoot异步使用@Async原理及线程池配置
  43. Questions d'entrevue de test avancé de Dachang, liste des compétences de base de l'entrevue Java,
  44. SpringBoot异步使用@Async原理及線程池配置
  45. Springboot utilise asynchrone le principe @ async et la configuration du pool de threads
  46. Détails de la découverte du Service d'application Dubbo 3 que Xiaobai peut également comprendre
  47. Springboot utilise asynchrone le principe @ async et la configuration du pool de threads
  48. 如何强大且优雅的搞定Linux文件系统,算法题 JVM,
  49. 太牛了,阿里P7架构师带你看透maven的来龙去脉,
  50. Oracle central et Oracle décentralisé
  51. java JavaBean
  52. Java wrapper type
  53. Java super keyword
  54. Java static keyword
  55. Java this keyword
  56. Java interface
  57. 太牛了,阿裏P7架構師帶你看透maven的來龍去脈,
  58. C'est génial, l'architecte Ali p7 vous montre à travers Maven.
  59. Comment traiter le système de fichiers Linux avec puissance et élégance, algorithme JVM,
  60. Usage of Java scanner