读取文件内容
public class App {
public static void main(String[] args) {
File file = new File("E:\\learn\\b.txt");
if (file.exists() && file.isFile()) {
System.out.println("文件存在");
/**
* BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
* 与
* BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
* 等价
*
* class FileReader extends InputStreamReader
* public FileReader(File file) throws FileNotFoundException {
* super(new FileInputStream(file));
* }
* */
try(BufferedReader bufferedReader = new BufferedReader(new FileReader(file)) ){
String line;
while ((line = bufferedReader.readLine()) != null){
System.out.println(line);
}
}catch (IOException e){
System.out.println(e.getMessage());
}
} else {
System.out.println("文件不存在");
}
}
}
文件重命名
public class App {
public static void main(String[] args) {
File file = new File("E:\\learn\\a.txt");
if(file.exists()){
System.out.println("文件存在");
File destFile = new File("E:\\learn\\b.txt");
boolean success = file.renameTo(destFile);
System.out.println(success);
}else{
System.out.println("文件不存在");
}
}
}
删除文件
public static void main(String[] args) {
File file = new File("E:\\learn\\b.txt");
if (file.exists() && file.isFile()) {
System.out.println("文件存在");
boolean success = file.delete();
if(success){
System.out.println("文件删除成功");
}
} else {
System.out.println("文件不存在");
}
}
复制文件
public static void main(String[] args) throws IOException {
File file = new File("E:\\learn\\hello.txt");
if (file.exists() && file.isFile()) {
/**
* 不会更新文件的修改时间,同源文件保持一致
* */
File copyFile = new File("E:\\learn\\hello_copy.txt");
Files.copy(file.toPath(), copyFile.toPath());
/**
* 会更新文件的修改时间
* */
File copyFile2 = new File("E:\\learn\\hello_copy2.txt");
try (FileChannel inputChannel = new FileInputStream(file).getChannel();
FileChannel outputChannel = new FileOutputStream(copyFile2).getChannel()
) {
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
}
}
}