Java 学习第四天

文件I/O

构造及使用

File 类

构造方法

  • File(pathname: String)
  • File(parent: String, child: String)
  • File(parent: File, child: String)

方法

  • exists(): boolean, 检测文件或文件夹是否存在
  • canRead(): boolean, 可读性
  • canWrite(): boolean, 可写性
  • length(): long, 返回文件大小
  • lastModified(): long, 最后修改时间
  • listFile(): File[], 返回当前对象路径下的文件
  • renameTo(dest: File): boolean, 重命名文件

PrintWriter类

构造方法

  • PrintWriter(file: File), 接受一个 File 对象进行构建
  • PrintWriter(filename: String)

方法

  • print(), 与 System.out.print() 一样的用法
  • println()
  • printf()

Scanner类

构造方法

  • Scanner(source: File)
  • Scanner(source: String)

方法

  • close() 关闭这个扫描器
  • hasNext(): boolean 检测这个扫描器还有无可读的内容
  • useDelimiter(pattern: String), 设置分隔模式

替换文本(待完善)

  • 需求: 编写一个程序, 从命令行接受参数, 实现对文件内容替换, 如

java ReplaceFileContents oldString newString sourceFile targetFile

将实现对 sourceFile 中的 oldString 替换为 newString, 并保存到 targetFile 中.

  • ReplaceFileContents.java
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    /*
    ReplaceFileContents.java
    */
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.Scanner;

    public class ReplaceFileContents {
    public static void main(String[] args) throws FileNotFoundException {
    String currentString = args[0];
    String replaceString = args[1];
    String oldFileName = args[2];
    String newFileName = args[3];

    File oldFile = new File(oldFileName);
    File newFile = new File(newFileName);
    PrintWriter file = new PrintWriter(newFile);
    Scanner input = new Scanner(oldFile);

    while (input.hasNext()){
    file.println(input.nextLine().replaceAll(currentString,replaceString));
    }
    file.close();
    }
    }
  • old.txt
    1
    2
    3
    my name is ljguo,
    ljguo is me,
    ljguo love gxx.

    javac ReplaceFileContents.java
    java ReplaceFileContents ljguo LJGUO old.txt new.txt

会在当前目录下生成文件new.txt, 内容为

1
2
3
my name is LJGUO,
LJGUO is me,
LJGUO love gxx.