本次作业主要复习了输入流输出流的内容
作业要求:
- 编写MyCP.java 实现类似Linux下cp XXX1 XXX2的功能,要求MyCP支持两个参数:
- java MyCP -tx XXX1.txt XXX2.bin 用来把文本文件(内容为十进制数字)转化为二进制文件
- java MyCP -xt XXX1.bin XXX2.txt 用来二进制文件把转化为文本文件(内容为十进制数字)
一开始没有使用-tx等命令,结果如上图
后来加入
结果如上图。
实验问题:
做实验的时候输出的二进制数数位不对,小数字的代码位数不对,无法解决
后来重写了代码,发现是i的判断出了问题。
import java.io.*;
import java.*;
public class MyCP{
public static void main(String[] args) throws IOException {
String filepath = "20175301/a.txt";
String s =dataInputStream(filepath);
FileOutputStream fps = new FileOutputStream("b.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();
}
}
import java.*;
public class MyCP{
public static void main(String[] args) throws IOException {
String filepath = "20175301/a.txt";
String s =dataInputStream(filepath);
FileOutputStream fps = new FileOutputStream("b.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();
}
}
import java.io.*;public class MyCP{ public static void main(String[] args) throws IOException { string num; num = in.readLine(); if(num.equals("-xt")) { String filepath = "20175301/a.txt"; String s =dataInputStream(filepath); FileOutputStream fps = new FileOutputStream("b.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(); } }