Java和C++判断文件是否被占用

参考:

很多CSDN上的博客以及stackoverflow上的解决方法

Java

1. RandomAccessFile

try {
    File file = new File("E:\\javaprojects\\file.py");
    System.out.println(file.exists());
    RandomAccessFile raf = new RandomAccessFile(file, "rw");
    raf.close();
    System.out.println("File not being used");
} catch (Exception e) {
    System.out.println("File being used");
}

2. renameTo

try {
    File file = new File("E:\\javaprojects\\file.py");
    System.out.println(file.exists());
    File newfile = new File("E:\\javaprojects\\file.py");
    if (file.renameTo(newfile)) {
        System.out.println("File not being used");
        newfile.renameTo(file);
    } else {
        System.out.println("File being used");
    }
} catch(Exception e) {
    e.printStackTrace();
}

3. FileWriter

try {
    File file = new File("E:\\javaprojects\\file.py");
    System.out.println(file.exists());
    FileWriter fw = new FileWriter(file);
    fw.close();
    System.out.println("File not being used");
} catch(IOException e) {
    System.out.println("File being used");
}

C++

// ifstream::is_open
#include      // std::cout
#include       // std::ifstream

int main () {
  std::ifstream ifs ("test.txt");

  if (ifs.is_open()) {
    // print file:
    char c = ifs.get();
    while (ifs.good()) {
      std::cout << c;
      c = ifs.get();
    }
  }
  else {
    // show message:
    std::cout << "Error opening file";
  }
  return 0;
}

你可能感兴趣的:(笔记)