编写MyCP.java 实现类似Linux下cp XXX1 XXX2的功能

  • 前置知识
    • cp命令:
      • 作用:cp指令用于复制文件或目录,如同时指定两个以上的文件或目录,且最后的目的地是一个已经存在的目录,则它会把前面指定的所有文件或目录复制到此目录中。若同时指定多个文件或目录,而最后的目的地并非一个已存在的目录,则会出现错误信息。
      • 参数:cp指令根据参数选择功能

  • 具体实现

    • 产品代码:
    import java.io.*;
    
     public class MyCP {
     public static void main(String args[]) {
         String choose = args[0];
         //获得第一个参数
         String File1 = args[1];
         //获得第二个参数:文件名
         String File2 = args[2];
         //获得第三个参数:文件名
         File sourceFile = new File(File1);
         //读取的文件
         File targetFile = new File(File2);
         //写入的文件
         int ch = 0;
         String result = "";
         //转换结果
         if (choose.equals("-tx")) {
             ch = 1;
         }
         else if (choose.equals("-xt")) {
             ch = 2;
         }
         //参数判断
         else {
             System.out.println("输入参数错误!");
             System.exit(0);
         }
         //如果参数输入错误,退出程序
         try {
             FileWriter out = new FileWriter(targetFile);
             //指向目的地的输出流
             FileReader in = new FileReader(sourceFile);
             //指向源的输入流
             BufferedReader infile = new BufferedReader(in);
             BufferedWriter outfile = new BufferedWriter(out);
             //缓冲流
             String number = infile.readLine();
             if (ch == 1) {
                 int n, temp = Integer.parseInt(number);
                 for (int i = temp; i > 0; i = i / 2) {
                     if (i % 2 == 0)
                         n = 0;
                     else
                         n = 1;
                     result = n + result;
                 }
             } else if (ch == 2) {
                 result = Integer.valueOf(number, 2).toString();
             }
             outfile.write(result);
             outfile.flush();
             outfile.close();
         } catch (IOException e) {
             System.out.println("Error " + e);
         }
     }
    

}


---

- 运行截图
- 参数为-tx时
![](https://img2018.cnblogs.com/blog/1592121/201904/1592121-20190427220104652-217300836.png)
![](https://img2018.cnblogs.com/blog/1592121/201904/1592121-20190427220110341-554248219.png)








- 参数为-xt时
![](https://img2018.cnblogs.com/blog/1592121/201904/1592121-20190427220123396-349756880.png)
![](https://img2018.cnblogs.com/blog/1592121/201904/1592121-20190427220127985-766980837.png)


---

- [码云托管链接](https://gitee.com/fzlzc/java2019/blob/master/src/MyCP.java)
posted @ 2019-04-27 22:04  20175214lzc  阅读(326)  评论(1编辑  收藏  举报