java成长日记(7)

  这几天雾霾天,不能出去锻炼,窝在宿舍无聊死了- -于是在昨天下午,为了打发这无聊的时光,于是我开始接触java中关于文件输入输出流的部分。

  接下来,我将以我们学校的java程序设计的实验四为例,分别写下接下来的三篇日记。

    

1 、编写一个 Java 应用程序,将已存在的扩展名为 helloWorld.txt 的文本文件
加密后存入文件 secret.txt 中。字符加密:大小写字母加密规则如下表,其它字
符加密前后不变。
helloWorld.txt 文件内容为:
Java is a powerful and versatile programming language for developing
software running on mobile devices, desktop computers, and servers.
Java is simple , object oriented, distributed, interpreted, robust, secure,
architecture neutral, portable, high performance, multithreaded, and dynamic. we
can write a program once and run it anywhere.

 代码的实现如下:

package Ava.experiment;

import java.io.*;

public class exper4has1 {
    public static void main(String[] args) throws IOException {
        FileReader old1_file = new FileReader("Ava/experiment/helloWorld.txt");
        FileReader old2_file = new FileReader("Ava/experiment/helloWorld.txt");
        FileWriter new_file = new FileWriter("Ava/experiment/secret.txt");
        int b , c;
        System.out.println("加密前的内容是:");
        while ((b = old1_file.read()) != -1) {
            new_file.write(Deciphering(b));
            System.out.print((char)b);
        }
        new_file.close();
        old1_file.close();
        System.out.println();
        System.out.println("加后前的内容是:");
        while ((c = old2_file.read()) != -1) {
            System.out.print((char)Deciphering(c));
        }
        old2_file.close();
    }

    public static int Deciphering(int len) {
        if (len >= 'a' && len < 'z') {
            return (len - 'a' + 1) % 26 + 'A';
        }  else if (len >= 'A' && len <= 'Z') {
            return (len - 'A' + 1) % 26 + 'a';
        } else return len;
    }
}

   解释:首先,创建一个加密方法Deciphering,根据ASCII码值来对传入的字符进行加密;之后,在主函数里先建立两个读取文件,文件路径引用你存储“helloWorld.txt”的文件路径;接着建立一个写入文件,路径保存在你要保存的地方,并命名为“secret.txt”;之后,让b查找helloWorld.txt里的每一个字符,因为.read()如果到达流的末尾,则返回  -1,我们依此作为循环的条件。在循环体里,我们用Deciphering的方法对字符加密,写入到secret.txt中,并将加密前的内容打印出来(记得把b强制转换成char类型,不然会输出一堆乱码)。然后记得关闭流(即.close()的方法)。然后我们接着读取helloWorld.txt的内容,并将其打印出来(即加密前的内容)。

运行结果如下:

它会在指定的路径新建一个 secret.txt:

其文件路径为 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值