首页 > 编程语言 >Java: Files

Java: Files

时间:2022-11-27 23:44:18浏览次数:37  
标签:Files Java System println File myObj class out

Java File Handling

The File class from the java.io package, allows us to work with files.

import java.io.File;  // Import the File class

File myObj = new File("filename.txt"); // Specify the filename

The File class has many useful methods for creating and getting information about files.For example:

MethodTypeDescription
canRead() Boolean Tests whether the file is readable or not
canWrite() Boolean Tests whether the file is writable or not
createNewFile() Boolean Creates an empty file
delete() Boolean Deletes a file
exists() Boolean Tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes
list() String[] Returns an array of the files in the directory
mkdir() Boolean Creates a directory

 

                         

Create a File

import java.io.File;  // Import the File class
import java.io.IOException;  // Import the IOException class to handle errors

public class CreateFile {
  public static void main(String[] args) {
    try {
      File myObj = new File("filename.txt");
if (myObj.createNewFile()) { -> Creates an empty file return true when create successful
        System.out.println("File created: " + myObj.getName());
      } else {
        System.out.println("File already exists.");
      }
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

specify the path of the file and use double backslashes to escape the "\" character (for Windows). On Mac and Linux you can just write the path, like: /Users/name/filename.txt

File myObj = new File("C:\\Users\\MyName\\filename.txt");

Write To a File

import java.io.FileWriter;   // Import the FileWriter class
import java.io.IOException;  // Import the IOException class to handle errors

public class WriteToFile {
  public static void main(String[] args) {
    try {
      FileWriter myWriter = new FileWriter("filename.txt");
      myWriter.write("Files in Java might be tricky, but it is fun enough!");
      myWriter.close();
      System.out.println("Successfully wrote to the file.");
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

Read a File

import java.io.File;  // Import the File class
import java.io.FileNotFoundException;  // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files

public class ReadFile {
  public static void main(String[] args) {
    try {
      File myObj = new File("filename.txt");
      Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
        String data = myReader.nextLine();
        System.out.println(data);
      }
      myReader.close();
    } catch (FileNotFoundException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

Get File Information

import java.io.File;  // Import the File class

public class GetFileInfo { 
  public static void main(String[] args) {
    File myObj = new File("filename.txt");
if (myObj.exists()) {
      System.out.println("File name: " + myObj.getName());
      System.out.println("Absolute path: " + myObj.getAbsolutePath());
      System.out.println("Writeable: " + myObj.canWrite());
      System.out.println("Readable " + myObj.canRead());
      System.out.println("File size in bytes " + myObj.length());
    } else {
      System.out.println("The file does not exist.");
    }
  }
}

Delete a File

import java.io.File;  // Import the File class

public class DeleteFile {
  public static void main(String[] args) { 
    File myObj = new File("filename.txt"); 
if (myObj.delete()) { 
      System.out.println("Deleted the file: " + myObj.getName());
    } else {
      System.out.println("Failed to delete the file.");
    } 
  } 
}

Delete a Folder

import java.io.File; 

public class DeleteFolder {
  public static void main(String[] args) { 
    File myObj = new File("C:\\Users\\MyName\\Test"); 
if (myObj.delete()) { 
      System.out.println("Deleted the folder: " + myObj.getName());
    } else {
      System.out.println("Failed to delete the folder.");
    } 
  } 
}

 

标签:Files,Java,System,println,File,myObj,class,out
From: https://www.cnblogs.com/ShengLiu/p/16931048.html

相关文章

  • java9
    Java9模块系统Java9最大的变化之一是引入了模块系统(Jigsaw项目)。模块就是代码和数据的封装体。模块的代码被组织成多个包,每个包中包含Java类和接口;模块的数据则包括资......
  • SpringBoot(四):java从配置文件中取值的方式
    一、SpringBoot项目中取yaml配置文件中的值application.yamltest:url:localhost:8080name:rootpassword:123456val:a:1b:2c:3TestC......
  • Java: Threads
    Threadsallowsaprogramtooperatemoreefficientlybydoingmultiplethingsatthesametime.CreatingaThreadTherearetwowaystocreateathread.Itcan......
  • Java: Regular Expressions
    Pattern Class-Definesapattern(tobeusedinasearch)Matcher Class-UsedtosearchforthepatternPatternSyntaxException Class-Indicatessyntaxe......
  • Java中使用正则表达式
    1、使用 java.util.regex.Pattern类的 compole(表达式)方法把正则表达式变成一个对象。//表达式对象:1个数字和1个字母连续Patternpattern=P......
  • Java入门代码练习
    一、第一个Java程序1、helloworldpublicclassHello{publicstaticvoidmain(String[]args){System.out.println("Helloworld!");}}2、变量i......
  • Java Excel导出动态自定义单元格样式
    根据表格内容定义单元格样式效果图:文章描述两种,一种创建生成时定义样式,另一种在excel在写入文件前修改样式关键代码一/***数据动态设置样式*......
  • 用Java打印一个9层空心菱形
    publicclassRhombus{publicstaticvoidmain(Stringargs[]){      for(inti=1;i<=5;i++){  //i表示层数      //空格个数    ......
  • Java: Exceptions - Try...Catch
    tryandcatch  Usetryandcatch:publicclassMain{publicstaticvoidmain(String[]args){try{int[]myNumbers={1,2,3};Syst......
  • Java: Wrapper Classes
    Wrapperclassesprovideawaytouseprimitivedatatypes(int, boolean,etc..)asobjects.PrimitiveDataTypeWrapperClassbyteByteshortShortint......