Java宝藏实验资源库(5)字符流

news2024/10/5 13:12:45

一、实验目的

  1. 掌握输入输出流的基本概念。
  2. 掌握字符流处理类的基本结构。
  3. 掌握使用字符流进行输入输出的基本方法。

二、实验内容过程及结果  

**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).

HexFormatException

VideoNote

Your program can be invoked from the command line with the Java source

code 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练习12_12测试

运行代码如下 :  

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class BraceStyleConverter {

    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Usage: java BraceStyleConverter <input_file>");
            return;
        }

        String inputFile = args[0];
        String outputFile = "converted_" + inputFile;

        try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
             FileWriter writer = new FileWriter(outputFile)) {

            String line;
            boolean insideBlock = false;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.startsWith("{")) {
                    insideBlock = true;
                }
                if (insideBlock) {
                    writer.write(line);
                    if (line.endsWith("}")) {
                        writer.write("\n");
                        insideBlock = false;
                    } else {
                        writer.write(" ");
                    }
                } else {
                    writer.write(line + "\n");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Conversion completed. Output written to " + outputFile);
    }
}

运行结果  

**12.18 (Add package statement) Suppose you have Java source files under the direc

tories 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(添加包语句)假设在目录下有Java源文件托利党第一章,第二章……, chapter34。编写一个程序来插入语句包章节;作为下面每个Java源文件的第一行目录章。假设第一章,第二章,…, chapter34都在根目录srcRootDirectory下。根目录和Chapteri目录可能包含其他文件夹和文件。使用以下命令命令运行程序:

java Exercise12_18 srcRootDirectory

 运行代码如下 :

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class PackageStatementInserter {

    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Usage: java PackageStatementInserter <srcRootDirectory>");
            return;
        }

        String srcRootDirectory = args[0];

        insertPackageStatements(srcRootDirectory);

        System.out.println("Package statements inserted successfully.");
    }

    public static void insertPackageStatements(String srcRootDirectory) {
        File rootDir = new File(srcRootDirectory);
        if (!rootDir.exists() || !rootDir.isDirectory()) {
            System.out.println("Invalid source root directory.");
            return;
        }

        File[] chapterDirs = rootDir.listFiles(File::isDirectory);
        if (chapterDirs == null) {
            System.out.println("No subdirectories found in the source root directory.");
            return;
        }

        for (File chapterDir : chapterDirs) {
            File[] javaFiles = chapterDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".java"));
            if (javaFiles == null) {
                continue; // Skip directories without Java files
            }

            for (File javaFile : javaFiles) {
                try {
                    insertPackageStatement(javaFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void insertPackageStatement(File javaFile) throws IOException {
        String originalFilePath = javaFile.getAbsolutePath();
        String tempFilePath = originalFilePath + ".tmp";

        try (BufferedReader reader = new BufferedReader(new FileReader(originalFilePath));
             FileWriter writer = new FileWriter(tempFilePath)) {

            // Insert package statement as the first line
            String packageStatement = getPackageStatement(javaFile);
            if (packageStatement != null) {
                writer.write(packageStatement + "\n");
            }

            // Copy the rest of the file
            String line;
            while ((line = reader.readLine()) != null) {
                writer.write(line + "\n");
            }
        }

        // Replace the original file with the modified temp file
        javaFile.delete();
        new File(tempFilePath).renameTo(new File(originalFilePath));
    }

    private static String getPackageStatement(File javaFile) throws IOException {
        String chapterName = javaFile.getParentFile().getName(); // Assumes chapter directories are named appropriately
        String packageName = "chapter" + chapterName; // Adjust as needed based on your directory structure

        return "package " + packageName + ";";
    }
}

 运行结果 

**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.    Supposechapter1, 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(删除包语句)假设Java源文件在目录chapter1, chapter2,…, chapter34。编写程序…删除语句包章节;在每个Java的第一行中目录chapteri下的源文件。假设第一,第二章,……、chapter34都在根目录srcRootDirectory下。根目录和chapteri目录可能包含其他文件夹和文件。使用执行以下命令运行程序:

java Exercise12_20 srcRootDirectory

 运行代码如下 :

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class PackageStatementRemover {

    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Usage: java PackageStatementRemover <srcRootDirectory>");
            return;
        }

        String srcRootDirectory = args[0];

        removePackageStatements(srcRootDirectory);

        System.out.println("Package statements removed successfully.");
    }

    public static void removePackageStatements(String srcRootDirectory) {
        File rootDir = new File(srcRootDirectory);
        if (!rootDir.exists() || !rootDir.isDirectory()) {
            System.out.println("Invalid source root directory.");
            return;
        }

        File[] chapterDirs = rootDir.listFiles(File::isDirectory);
        if (chapterDirs == null) {
            System.out.println("No subdirectories found in the source root directory.");
            return;
        }

        for (File chapterDir : chapterDirs) {
            File[] javaFiles = chapterDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".java"));
            if (javaFiles == null) {
                continue; // Skip directories without Java files
            }

            for (File javaFile : javaFiles) {
                try {
                    removePackageStatement(javaFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void removePackageStatement(File javaFile) throws IOException {
        String originalFilePath = javaFile.getAbsolutePath();
        String tempFilePath = originalFilePath + ".tmp";

        try (BufferedReader reader = new BufferedReader(new FileReader(originalFilePath));
             FileWriter writer = new FileWriter(tempFilePath)) {

            // Skip the first line (package statement)
            reader.readLine(); // Assuming the first line is always the package statement

            // Copy the rest of the file
            String line;
            while ((line = reader.readLine()) != null) {
                writer.write(line + "\n");
            }
        }

        // Replace the original file with the modified temp file
        javaFile.delete();
        new File(tempFilePath).renameTo(new File(originalFilePath));
    }
}

运行结果  

三、实验结论   

       通过本次实验实践了字符流输入输出功能的知识和操作,得到了调用子功能包时一定要注重效率,感悟到对程序的底层逻辑一定要了解,不能一味地求速学,该精学时还得筑牢基础。

 结语   

 喜欢的事情就要做到极致

决不能半途而废

!!!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1861910.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Reactor模型:网络线程模型演进

一&#xff0c;阻塞IO线程池模型&#xff08;BIO&#xff09; 这是传统的网络编程方案所采用的线程模型。 即有一个主循环&#xff0c;socket.accept阻塞等待&#xff0c;当建立连接后&#xff0c;创建新的线程/从线程池中取一个&#xff0c;把该socket连接交由新线程全权处理。…

HarmonyOS NEXT Developer Beta1配套相关说明

一、版本概述 2024华为开发者大会&#xff0c;HarmonyOS NEXT终于在万千开发者的期待下从幕后走向台前。 HarmonyOS NEXT采用全新升级的系统架构&#xff0c;贯穿HarmonyOS全场景体验的底层优化&#xff0c;系统更流畅&#xff0c;隐私安全能力更强大&#xff0c;将给您带来更高…

qmt量化交易策略小白学习笔记第44期【qmt编程之期货行情数据】

qmt编程之获取期货行情数据 qmt更加详细的教程方法&#xff0c;会持续慢慢梳理。 也可找寻博主的历史文章&#xff0c;搜索关键词查看解决方案 &#xff01; 获取行情数据 提示 使用该接口时&#xff0c;需要先订阅实时行情(subscribe_quote)或下载过历史行情(download_hi…

WEB界面上使用ChatGPT

&#xff08;作者&#xff1a;陈玓玏&#xff09; 开源项目&#xff0c;欢迎star哦&#xff0c;https://github.com/tencentmusic/cube-studio 随着大模型不断发展&#xff0c;现在无论写代码&#xff0c;做设计&#xff0c;甚至老师备课、评卷都可以通过AI大模型来实现了&…

5分钟带你部署一套Jenkins持续集成环境​

5分钟带你部署一套Jenkins持续集成环境 Jenkins是开源CI&CD软件领导者&#xff0c; 提供超过1000个插件来支持构建、部署、自动化&#xff0c; 满足任何项目的需要。 Jenkins的优点 持续集成和持续交付 作为一个可扩展的自动化服务器&#xff0c;Jenkins 可以用作简单的 CI…

【分布式文件系统HDFS】API 编程基础

目录 一、使用 HDFS API 完成以下程序设计并运行 1. 将 HDFS 文件系统目录/user/账户名下的文件 test1.txt 下载至本地文件系统目录/home/账户名/Desktop 下。 1.1 程序代码 1.2 运行截图 1.3 查看本地的test1.txt文件 2. 在 HDFS 文件系统上创建目录/test1 2.1 程序代码…

230个大模型招投标大单,前三令人意外

大模型市场争夺白热化&#xff0c;前三的座次每个月都在变。 2024年被认为是大模型的应用落地元年&#xff0c;大模型落地的进展一直备受瞩目&#xff0c;而大模型招投标信息被认为是其中的风向标。最近&#xff0c;数智前线通过中国政府采购网、中国招投标公共服务平台、天眼…

PS系统教程27

Photoshop与Camera Raw Camera本身是作为插件存在的&#xff0c;处理对象Raw格式&#xff08;高清格式的图片标准&#xff09; JPG是压缩格式 Camera是源数据包&#xff0c;无损高清数据包 通道 通道只有黑白灰三种颜色&#xff0c;图层类似于前台&#xff0c;通道就是后台…

Unity海面效果——2、菲涅尔水的介绍

Unity引擎制作海面效果 大家好&#xff0c;我是阿赵。 这一篇是说一下菲涅尔水的基本原理。 延续之前的例子&#xff0c;我场景里面有天空盒、小岛和水面。 一、菲涅尔反射原理介绍 从摄像机的角度看去&#xff0c;看不同的海面的点&#xff0c;摄像机和海面形成的夹角会发生变…

electron-builder 打包过慢解决

报错内容如下 > 6-241.0.0 build > electron-builder • electron-builder version24.13.3 os10.0.22631 • loaded configuration filepackage.json ("build" field) • writing effective config filedist\builder-effective-config.yaml • pack…

Ansible自动化运维,(1)模块

ansible是基于Python语言实现的&#xff0c;模块化&#xff1a;调用特定的模块完成特定的任务&#xff0c;支持自定义模块&#xff0c;可使用任何编程语言写模块(账号&#xff0c;软件等)。部署简单&#xff0c;基于python和SSH&#xff0c;相对安全&#xff0c;基于OpenSSH。 …

Qt 5.14.2+Android环境搭建

1. 安装QT5.14.2的过程中&#xff0c;选中套件&#xff08;kit&#xff09; qt for android。 如果已经安装了qt creator但没有安装该套件&#xff0c;可以找到在qt安装目录下的MaintenanceTool.exe&#xff0c;运行该程序添加套件。 2. 安装jdk8&#xff0c;android sdk&…

SAP系统中的应付账款(与MM集成,关账操作)

1. 与物料管理的集成 Plant: 工厂是后勤中的位于中心位置的组织对象&#xff0c;一个“工厂”可以是公司内的一个作业区&#xff0c;或一个分支机构。一个“工厂”可以是一个中央交付仓库&#xff0c;可以是一个区域的销售营业部&#xff0c;一个制造工厂&#xff0c;一个集团…

【Transformer Debugger】OpenAI开源大模型调测工具--可以在训练大模型之前理解模型的运行情况并干预

背景 OpenAI开源了一个全新的大模型调测工具&#xff1a;Transformer Debugger。这个工具可以帮助开发者调测大模型的推理情况&#xff0c;帮助我们理解模型的输出并提供一定的解释支持https://github.com/openai/transformer-debugger 应用场景 这一工具在多个领域展现出广…

寄存器组(堆栈指针寄存器小解)

寄存器组&#xff08;堆栈指针寄存器小解&#xff09; 寄存器组栈是向下伸长的出入栈操作时候的SP寄存器 例子 寄存器组 主堆栈指针&#xff08;MSP&#xff09;&#xff1a;这是缺省的堆栈指针&#xff0c;它由 OS 内核、异常服务例程以及所有需要特权访问的 应用程序代码来使…

初阶 《操作符详解》 10. 逗号表达式

10. 逗号表达式 exp1, exp2, exp3, …expN 注&#xff1a; 1.逗号表达式&#xff0c;就是用逗号隔开的多个表达式 2.逗号表达式&#xff0c;从左向右依次执行&#xff0c;整个表达式的结果是最后一个表达式的结果 代码1 #include <stdio.h> int main() {int a 1;int b…

Flink 状态管理

一、状态 流式计算分为无状态和有状态两种情况。无状态的计算观察每个独立事件&#xff0c;并且根据最后一个事件输出结果。例如&#xff0c;流处理应用程序从传感器接收温度读数&#xff0c;并在温度超过90度时发出告警。有状态的计算则会基于多个事件输出结果。例如&#xf…

为什么永远不会有语言取代 C/C++?

每个 CPU 都带有一种称为 ISA&#xff08;指令集架构&#xff09;汇编的电路语言。ISA 程序集是一种硬件语言&#xff0c;由基本数据操作、数学计算和结构化编程&#xff08;即 jmp&#xff09;的操作组成。但是&#xff0c;为每个计算需求编写汇编代码无疑是耗时的&#xff0c…

DevOps CMDB平台整合Jira工单

背景 在DevOps CMDB平台建设的过程中&#xff0c;我们可以很容易的将业务应用所涉及的云资源&#xff08;WAF、K8S、虚拟机等&#xff09;、CICD工具链&#xff08;Jenkins、ArgoCD&#xff09;、监控、日志等一次性的维护到CMDB平台&#xff0c;但随着时间的推移&#xff0c;…

vue3-openlayers marker 光晕扩散(光环扩散)(postrender 事件和 render 方法)

本篇介绍一下使用 vue3-openlayers marker 光晕扩散&#xff08;光环扩散&#xff09;&#xff08;postrender 事件和 render 方法&#xff09; 1 需求 marker 光晕扩散&#xff08;光环扩散&#xff09; 2 分析 marker 光晕扩散&#xff08;光环扩散&#xff09;使用 post…