首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Java 文件操作完全指南:控制台輸入、複製、讀寫、重命名、移動、刪除、XML 解析實戰代碼

     編輯:Java 程式設計入門

一、獲取控制台用戶輸入

public String getInputMessage() throws IOException {
    System.out.print("請輸入命令:");
    byte[] buffer = new byte[1024];
    int count = System.in.read(buffer);
    // 去除換行符(Windows \r\n 佔 2 字節,Linux \n 佔 1 字節,這裡簡化處理)
    char[] ch = new char[count - 2];
    for (int i = 0; i < count - 2; i++) ch[i] = (char) buffer[i];
    return new String(ch);
}

缺點:不支持中文輸入(需用 InputStreamReader + 指定編碼)。

二、文件複製(流式,支持二進制/文本/中文)

public void copyFile(String src, String dest) throws IOException {
    try (FileInputStream in = new FileInputStream(src);
         FileOutputStream out = new FileOutputStream(dest)) {
        byte[] buffer = new byte[1024];
        int len;
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
    }
}

✅ 支持 txt、XML、jpg、doc 等任意格式;✅ try-with-resources 自動關閉資源(JDK 7+)。

三、文件寫入

1. PrintStream 簡單行寫入

public void printStreamDemo() {
    try (PrintStream p = new PrintStream(new FileOutputStream("D:/test.txt"))) {
        for (int i = 0; i < 10; i++) p.println("This is " + i + " line");
    } catch (FileNotFoundException e) { e.printStackTrace(); }
}

2. StringBuffer + 指定編碼(解決中文亂碼)

public void stringBufferDemo() throws IOException {
    File file = new File("/root/sms.log");
    if (!file.exists()) file.createNewFile();
    try (FileOutputStream out = new FileOutputStream(file, true)) { // true = 追加模式
        for (int i = 0; i < 10000; i++) {
            StringBuffer sb = new StringBuffer();
            sb.append("這是第").append(i).append("行...");
            out.write(sb.toString().getBytes("UTF-8"));
        }
    }
}

四、文件重命名

public void renameFile(String path, String oldName, String newName) {
    if (oldName.equals(newName)) return;
    File oldFile = new File(path, oldName);
    File newFile = new File(path, newName);
    if (newFile.exists()) {
        System.out.println(newName + " 已存在!");
    } else {
        oldFile.renameTo(newFile);
    }
}

五、移動文件(剪切語義:源目錄不再保留)

public void moveFile(String fileName, String oldPath, String newPath, boolean overwrite) {
    if (oldPath.equals(newPath)) return;
    File src = new File(oldPath, fileName);
    File dest = new File(newPath, fileName);
    if (dest.exists()) {
        if (overwrite) src.renameTo(dest);
        else System.out.println("目標目錄已存在:" + fileName);
    } else {
        src.renameTo(dest);
    }
}

六、文件讀取

1. FileInputStream(二進制/通用)

public String readByFileInputStream(String path) throws IOException {
    File file = new File(path);
    if (!file.exists() || file.isDirectory()) throw new FileNotFoundException();
    try (FileInputStream fis = new FileInputStream(file)) {
        byte[] buf = new byte[1024];
        StringBuilder sb = new StringBuilder();
        int len;
        while ((len = fis.read(buf)) != -1) {
            sb.append(new String(buf, 0, len, StandardCharsets.UTF_8));
        }
        return sb.toString();
    }
}

2. BufferedReader(文本行讀取,效率更高)

public String readByBufferedReader(String path) throws IOException {
    File file = new File(path);
    if (!file.exists() || file.isDirectory()) throw new FileNotFoundException();
    try (BufferedReader br = new BufferedReader(new FileReader(file))) {
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
        }
        return sb.toString();
    }
}

3. dom4j 解析 XML

public Document readXml(String path) throws DocumentException, IOException {
    File file = new File(path);
    try (BufferedReader br = new BufferedReader(new FileReader(file))) {
        SAXReader reader = new SAXReader();
        return reader.read(br);
    }
}

七、創建文件/目錄

// 創建目錄(含多級)
public void createDir(String path) {
    new File(path).mkdirs();
}

// 創建文件
public void createFile(String path, String fileName) throws IOException {
    File file = new File(path, fileName);
    if (!file.exists()) file.createNewFile();
}

八、刪除文件/目錄(遞歸刪除非空目錄)

// 刪除文件
public void deleteFile(String path, String fileName) {
    File file = new File(path, fileName);
    if (file.exists() && file.isFile()) file.delete();
}

// 遞歸刪除目錄
public void deleteDir(String path) {
    File dir = new File(path);
    if (dir.exists()) {
        File[] files = dir.listFiles();
        if (files != null) {
            for (File f : files) {
                if (f.isDirectory()) deleteDir(f.getAbsolutePath());
                else f.delete();
            }
        }
        dir.delete();
    }
}

最佳實踐總結

  • 優先使用 try-with-resources (JDK 7+) 自動管理資源關閉
  • 文本操作指定編碼(UTF-8),避免跨平台亂碼
  • 大文件複製/讀寫:使用 FileChannel.transferTo/From (NIO) 或緩衝區 64KB+
  • 路徑拼接用 new File(parent, child) 或 Paths.get(),避免手動拼接分隔符
  • NIO.2 (JDK 7+) Files 工具類:Files.copy/move/delete/readAllLines/write 更簡潔、支持屬性複製、原子移動
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved