2021.06.07上机题
题目描述:
17.17代码:
package Practice;
import java.io.*;
public class Ch17Q17 {
public static void main(String[] args) {
try {
FileOutputStream MyFile = new FileOutputStream(new File("outFile.dat"));
BitOutputStream MyOutString = new BitOutputStream(MyFile);
for (int i = 0; i < 10; i++) {
MyOutString.writeBit('0');
MyOutString.writeBit('1');
}
MyOutString.writeBit("01010101010101011");
MyOutString.close();
}
catch (IOException io) {
io.getStackTrace();
}
System.out.println("Finish");
}
}
class BitOutputStream extends FilterOutputStream {
private int count = 0;
private int value;
private int flag = 1; //00000001
public BitOutputStream(OutputStream out) {
super(out);
}
public void writeBit(char bit) throws IOException {
count++;
value = value << 1;
if (bit == '1')
value = value | flag;
if (count == 8) {
out.write(value);
count = 0;
}
}
public void writeBit(String string) throws IOException {
for (int i = 0; i < string.length(); i++)
writeBit(string.charAt(i));
}
public void close() throws IOException {
if (count > 0) {
value = value << (8 - count);
out.write(value);
}
super.close();
}
}
17.10代码:
import java.io.*;
//java Exercise17_10 test.mp4 3
public class Exercise17_10 {
public static void main(String[] args) throws java.lang.Exception {
if (args.length != 2) {
System.out.println("Usage: java Exercise17_10 SourceFile numberOfPieces");
System.exit(1);
}
try (
BufferedInputStream input = new BufferedInputStream(new FileInputStream(
new File(args[0])));
) {
int numberOfPieces = Integer.parseInt(args[1]);
System.out.println("File size: " + input.available() + " bytes");
long fileSize = input.available();
int splitFileSize = (int)
Math.ceil(1.0 * fileSize / numberOfPieces);
for (int i = 1; i <= numberOfPieces; i++) {
try (
BufferedOutputStream output = new BufferedOutputStream(
new FileOutputStream(new File(args[0] + "." + i)));
) {
int value;
int count = 0;
while (count++ < splitFileSize && (value = input.read()) != -1) {
output.write(value);
}
}
}
}
}
}