使用Java实现文件操作:读写、复制和删除
在Java中,我们可以使用java.io.File
类进行文件操作。以下是一些基本的文件操作方法:
创建文件:
File file = new File("path_to_file"); // path can be relative or absolute
if (file.exists()) { // check if the file already exists
System.out.println("File already exists.");
} else {
file.createNewFile(); // create a new file, if it doesn't exist yet
System.out.println("File created successfully.");
}
读写文件:
```java
// Write to file
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file)))) {
writer.write(“Hello, World!”);
writer.newLine(); // write a newline character
writer.flush(); // flush the buffer to ensure the data is written immediately
}
catch (IOException e) {
System.out.println(“Error occurred while writing to file: “ + e.getMessage());
}
// Read from file
try (BufferedReader reader = new BufferedReader(new FileReader(file)))) {
String line;
while ((line = reader.readLine()) != null) { // read until the end of file or a null value
System.out.println(line);
}
}
catch (IOException e) {
System.out.println(“Error occurred while reading from file: “ + e.getMessage());
}
3. **复制文件**:
```java
// Copy file to another location using absolute path
try (FileInputStream fis = new FileInputStream(file));
FileOutputStream fos = new FileOutputStream("path_to_destination_file")) as FileInputStream, FileOutputStream {
byte[] buffer = new byte[1024]; // define buffer size
int bytesRead = fis.read(buffer); // read from source file
if (bytesRead != -1) { // if data is read successfully
fos.write(buffer, 0, bytesRead); // write to destination file
System.out.println("File copied successfully.");
} else {
System.out.println("Error occurred while copying file: " + fis.readError()));
}
}
catch (IOException e) {
System.out.println("Error occurred while copying file: " + e.getMessage());
}
- 删除文件:
// Delete file using absolute path
try {
File fileToDelete = new File("path_to_file"); // replace with your file's path
if (fileToDelete.exists()) { // check if the file exists
fileToDelete.delete(); // delete the file
System.out.println("File deleted successfully.");
} else {
System.out.println("Error occurred while deleting file: File doesn't exist.");
}
} catch (IOException e) {
System.out.println("Error occurred while deleting file: " + e.getMessage());
}
请确保提供正确的文件路径,否则可能会抛出FileNotFoundException
。
还没有评论,来说两句吧...