作业要求
- 编写MyCP.java 实现类似Linux下cp XXX1 XXX2的功能,要求MyCP支持两个参数:
- java MyCP -tx XXX1.txt XXX2.bin 用来把文本文件(内容为十进制数字)转化为二进制文件
- java MyCP -xt XXX1.bin XXX2.txt 用来二进制文件把转化为文本文件(内容为十进制数字)
思路
- 从指定文件读取字符串型变量,根据命令行输入的“-tx”或“-xt”判断,将十进制转为二进制或将二进制转为十进制,再输出。
产品代码
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);
}
}
}
测试结果
java MyCP -tx XXX1.txt XXX2.bin
java MyCP -xt XXX1.bin XXX2.txt
遇到的问题
1.问题:当在idea中运行的时候,出现了这个问题。
解决方案:询问同学发现也有这种情况,具体原因是什么不清楚,但是在虚拟机中可以运行。
2.问题:第一次在虚拟机中运行出现了无法加载主类。
解决方案:最开始把编译出来的文件和txt与bin分开了,帮他们放一起时又可以了。