面向对象程序设计(双语)|| 实验八:字符流(Java版)
一、实验目的
- 掌握输入输出流的基本概念。
- 掌握字符流处理类的基本结构。
- 掌握使用字节符进行输入输出的基本方法。
二、实验内容、过程及结果
**12.12 (Reformat Java source code) Write a program that converts the Java source code from the next-line brace style to the end-of-line brace style. For example, the following Java source in (a) uses the next-line brace style. Your program converts it to the end-of-line brace style in (b).
Your program can be invoked from the command line with the Java sourcecode file as the argument. It converts the Java source code to a new format. For example, the following command converts the Java source-code file Test.java to the end-of-line brace style.
java Exercise12_12 Test.java
**12.12(重新新格式化Java源代码)编写一个程序,将 Java 源代码的次行块风格转换成行尾块风格。例如,图 a 中的 Java 源代码使用的是次行块风格。程序将它转换成图 b 中所示的行尾块形式。
程序可以从命令行调用,以 Java 源代码文件作为其参数。它会将这个 Java 源代码变成新 的格式。例如,下面的命令将 Java 源代码文件 Testjava 转变成行尾块风格:
java Exerc1sel2_l2 Test.java
import java.io.*;
import java.util.Scanner;public class Exercise12_12 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("请输入Java源代码的绝对文件路径: ");String filePath =input.nextLine();try {// 读取输入文件BufferedReader reader =new BufferedReader(new FileReader(filePath));StringBuilder context =new StringBuilder();String line="";while ((line = reader.readLine()) != null) {context.append(line).append("\n");}reader.close();// 转换为行尾块风格String convertedContent =convertToLineBlockStyle(context.toString());// 将转换后的内容写回文件BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));writer.write(convertedContent);writer.close();System.out.println("Java源代码已成功转换为行尾块风格!");} catch (IOException e) {System.out.println("转换Java源代码出错!");e.printStackTrace();}}private static String convertToLineBlockStyle(String string) {// 移除新行上的左边的大括号string =string.replaceAll("\\n\\s*\\{", " {");// 移除左括号前的不必要的空格和制表符string =string.replaceAll("\\s*\\(", "(");return string;}
}
运行结果截图
**12.18 (Add package statement) Suppose you have Java source files under the directories chapter1, chapter2, . . . , chapter34. Write a program to insert the statement package chapteri; as the first line for each Java source file under the directory chapteri. Suppose chapter1, chapter2, . . . , chapter34 are under the root directory srcRootDirectory. The root directory and chapteri directory may contain other folders and files. Use the following command to run the program: java Exercise12_18 srcRootDirectory
**12.18 (添加包语句)假设在目录 chapterl, chapter2, … ,chapteri 下面有 Java 源文件。编写一个程序,对在目录 chapteri下面的 Java 源文件的第一行添加语句 “ pachage chapter!;"。假定 chapterl, chapter2, ... , chapter34在根目录 srcRootDirectory 下面。根目录和 chapteri 目录可能包含其他目录和文件。使用下面命令来运行程序: java Exercisel2_18 srcRootDirectory。
import java.io.*;
import java.util.*;
public class Exercise12_18 {public static void main(String[] args) {// 获取根目录路径String srcRootDirectory;BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));System.out.print("请输入根目录路径:");try {srcRootDirectory =reader.readLine();} catch (IOException e) {System.out.println("读取失败!");return;}// 遍历章节目录for (int i = 1;i<=34; i++) {String chapterDirectory =srcRootDirectory + "/chapter" + i;// 检查目录是否存在File directory = new File(chapterDirectory);if (!directory.exists() || !directory.isDirectory()) {continue;}// 获取目录下的Java源文件File[] files = directory.listFiles();List<File> javaFilesList =new ArrayList<>();// 遍历目录下的所有文件for (File file : files) {// 检查文件名是否以 ".java" 结尾if (file.isFile() && file.getName().toLowerCase().endsWith(".java")) {javaFilesList.add(file);}}// 将 List 转换为数组File[] javaFiles = javaFilesList.toArray(new File[0]);// 处理每个Java源文件if (javaFiles != null) {for (File javaFile : javaFiles) {try {// 读取Java源文件内容BufferedReader fileReader = new BufferedReader(new FileReader(javaFile));String context = "";String line="";while ((line = fileReader.readLine()) != null) {context= context+line + "\n";}fileReader.close();// 添加package语句context = "package chapter" + i + ";\n" + context;// 写回文件BufferedWriter fileWriter = new BufferedWriter(new FileWriter(javaFile));fileWriter.write(context);fileWriter.close();System.out.println("已修改文件:" + javaFile.getAbsolutePath());} catch (IOException e) {System.out.println("处理文件时发生错误:" + javaFile.getAbsolutePath());e.printStackTrace();}}}}}
}
**12.20 (Remove package statement) Suppose you have Java source files under the directories chapter1, chapter2, . . . , chapter34. Write a program to remove the statement package chapteri; in the first line for each Java source file under the directory chapteri. Suppose chapter1, chapter2, . . . , chapter34 are under the root directory srcRootDirectory. The root directory and chapteri directory may contain other folders and files. Use the following command to run the program: java Exercise12_20 srcRootDirectory.
**12.20 (删除包语句)假设在目录 chapteri,chapter2,...,chapter34 下面有 Java 源文件。编写一个 程序,对在目录 chapteri 下面的 Java 源文件删除其第一行包语句 “ pachage chapteri;”。 假定 chapter1,chapter2, …,chapter34 在 根 目 录 srcRootDirectory 下 面。根 目 录 和 chapteri 目录可能包含其他目录和文件。使用下面命令来运行程序: java Exercisel2_20 srcRootDirectory
import java.io.*;
import java.util.*;public class Exercise12_20 {public static void main(String[] args) {// 获取根目录路径String srcRootDirectory;BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));System.out.print("请输入根目录路径:");try {srcRootDirectory =reader.readLine();} catch (IOException e) {System.out.println("读取失败!");return;}// 遍历章节目录for (int i = 1; i <= 34; i++) {String chapterDirectory =srcRootDirectory + "/chapter" + i;// 检查目录是否存在File directory = new File(chapterDirectory);if (!directory.exists() || !directory.isDirectory()) {continue;}// 获取目录下的Java源文件File[] files = directory.listFiles();List<File> javaFilesList = new ArrayList<>();//加强for循环遍历下面Java文件for (File file : files) {// 检查文件名是否Java文件if (file.isFile() && file.getName().toLowerCase().endsWith(".java")) {javaFilesList.add(file);}}// 将 List 转换为数组File[] javaFiles = javaFilesList.toArray(new File[0]);// 处理每个Java源文件if (javaFiles !=null) {for (File javaFile : javaFiles) {try {// 读取Java源文件内容BufferedReader fileReader = new BufferedReader(new FileReader(javaFile));StringBuilder context =new StringBuilder();String line="";while ((line = fileReader.readLine()) != null) {// 跳过包语句if (!line.trim().startsWith("package")) {context.append(line).append("\n");}}fileReader.close();// 写回文件BufferedWriter fileWriter = new BufferedWriter(new FileWriter(javaFile));fileWriter.write(context.toString());fileWriter.close();System.out.println("已修改文件:" + javaFile.getAbsolutePath());} catch (IOException e) {System.out.println("处理文件时发生错误:" + javaFile.getAbsolutePath());e.printStackTrace();}}}}}
}
三、实验结论
通过本次实验实践了输入输出流、字符流处理类的基本结构、字节符进行输入输出的基本方法的知识和操作,得到了一些有关代码处理和文件修改的经验,在实践过程中,我学到了如何读取用户输入并将其作为程序的输入。这是一个基本的输入输出操作,但对于编写交互式程序非常有用,我会使用”BufferedReader”来读取用户输入,并通过异常处理来处理可能的输入错误,了解了如何遍历目录和文件,并根据特定的条件进行筛选和处理。在这个实验中,我需要遍历章节目录,并找到其中的Java源文件,通过使用`File`类和一些条件判断,我获取到了所需的文件列表,这个实践让我更加熟悉了文件操作的相关方法和技巧;通过使用”BufferedReader”和”BufferedWriter”类,我读取和写入文件的内容,并将其存储到一个”StringBuilder”中,然后,再将修改后的内容写回到文件中,在未来的编程中,我可以进一步改进我的代码,我可以考虑使用更高效的方法来遍历目录和文件,以提高程序的性能。