MyCP

一、作业要求

编写MyCP.java 实现类似Linux下cp  XXX1 XXX2的功能,要求MyCP支持两个参数:
- java MyCP -tx XXX1.txt XXX2.bin  用来把文本文件(内容为十进制数字)转化为二进制文件
- java MyCP -xt XXX1.bin XXX2.txt  用来二进制文件把转化为文本文件(内容为十进制数字)

二、代码

import java.io.*;
import java.*;
public class MyCP{
    public static void main(String[] args) throws IOException {
        String filepath = "C:\十进制.txt";
        String s =dataInputStream(filepath);
        FileOutputStream fps = new FileOutputStream("C:\二进制.txt");
        fps.write(s.getBytes());
        fps.close();
    }
    public static String dataInputStream(String filepath) throws IOException {
        File file = new File(filepath);
        DataInputStream dps = new DataInputStream(new FileInputStream(file));
        StringBuilder byData = new StringBuilder();
        byte bt = 0;
        for(int i=0;i<file.length();i++) {
            bt = dps.readByte();
            String str = Integer.toBinaryString(bt);
            if(str.length() == 1) {
                str = "0"+str;
            }
            byData.append(str.toUpperCase());
        }
        return byData.toString();
    }
}

三、运行结果

原文地址:https://www.cnblogs.com/20175228lyc/p/10786523.html