Xử lý file trong lập trình Java

Giới thiệu nội dung bài viết

Trong lập trình Java, có các đối tượng file dùng để thao tác đọc, mở đóng file. Chúng ta có thể lưu trữ giá trị của người dùng vào file. Sau đó chương trình sẽ đọc các file đó và hiển thị cho người dùng.


Để hiểu rõ hơn về File cũng như các cách thực hiện với File trong lập trình hướng đối tượng Java bao gồm cách tạo file, ghi và đọc các giá trị trong file, cách lấy thông tin của một file bất kì nào đó, hay cách để xoá một file sẵn có. Bài viết dưới đây với các ví dụ minh hoạ cụ thể trong mỗi thao tác với File kèm theo một video demo tạo File cuối bài sẽ giúp các bạn dễ dàng nắm vững kiến thức này trong quá trình phải học một lượng lớn các kiến thức lập trình Java từ cơ bản đến nâng cao khác.

  • Tạo file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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()) {
        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();
    }
  }
}
  • Ghi các giá trị vào file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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();
    }
  }
}
  • Đọc các giá trị từ file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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();
    }
  }
}
  • Lấy thông tin của file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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.");
    }
  }
}
  • Xoá một file
1
2
3
4
5
6
7
8
9
10
11
12
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.");
    } 
  } 
}

2. Video demo tạo File trong Java

3. Source code

Sourcecode


Mọi người hãy Subscribe kênh youtube dưới đây nhé để cập nhật các video mới nhất về kỹ thuật và kỹ năng mềm

Các khoá học lập trình MIỄN PHÍ tại đây


Comments