所以我在学校的java课程中通过我的方式工作。为了更好地理解代码应该做什么,引用它:
“(拆分文件)假设您要将一个巨大的文件(例如,一个10 GB的AVI文件)备份到CD-R。您可以通过将文件拆分成较小的部分并分别备份这些部分来实现它编写一个实用程序,使用以下命令将大文件拆分为较小的文件: java ClassName SourceFile numberOfPieces
该命令会创建文件 SourceFile.1 , SourceFile2 ...等等
现在要清楚了。这篇文章绝不是试图找到问题的“解决方案”。我解决了它(用我所知道的)。而且我只想更加关注编写代码时遇到的一些问题。
代码,如果你想看一下。
欢迎所有反馈, 祝你有美好的一天! :)
package oblig2;
import java.io.*;
import java.util.*;
public class Test {
/**
* Main method
*
* @param args[0] for source file
* @param args[1] for number of pieces
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// The program needs to be executed with two parameters in order to
// work. This sentence check for it.
if (args.length != 2) {
System.out.println("Usage: java Copy sourceFile numberOfPieces");
System.exit(1);
}
// Check whether or not the sourcefile exists
File sourceFile = new File(args[0]);
if (!sourceFile.exists()) {
System.out.println("Source file " + args[0] + " does not exist");
System.exit(2);
}
// Need an Array to store all the new files that is supposed to contain
// parts of the original file
ArrayList<File> fileArray = new ArrayList<File>();
// All the new files need their own output(or do they?)
ArrayList<BufferedOutputStream> outputArray = new ArrayList<BufferedOutputStream>();
// Using randomAccessFile on the sourcefile to easier read parts of it
RandomAccessFile inOutSourceFile = new RandomAccessFile(sourceFile,
"rw");
// This loop changes the name for the new files, so they match the
// sourcefile with an appended digit
for (int i = 0; i < Integer.parseInt(args[1]); i++) {
String nameAppender = String.valueOf(i);
String nameBuilder;
int suffix = args[0].indexOf(".");
nameBuilder = args[0].substring(0, suffix);
fileArray.add((new File(nameBuilder + nameAppender + ".dat")));
}
// Here i create the output needed for all the new files
for (int i = 0; i < Integer.parseInt(args[1]); i++) {
outputArray.add(new BufferedOutputStream(new FileOutputStream(
new File(fileArray.get(i).getAbsolutePath()))));
}
// Now i determine in how many parts the sourcefile needs to be split,
// and the size of each.
float size = inOutSourceFile.length();
double parts = Integer.parseInt(args[1]);
double partSize = size / parts;
int r, numberOfBytesCopied = 0;
// This loop actually does the job of copying the parts into the new
// files
for (int i = 1; i <= parts; i++) {
while (inOutSourceFile.getFilePointer() < partSize * i) {
r = inOutSourceFile.readByte();
outputArray.get(i - 1).write((byte) r);
numberOfBytesCopied++;
}
}
// Here i close the input and outputs
inOutSourceFile.close();
for (int i = 0; i < parts; i++) {
outputArray.get(i).close();
}
// Display the operations
System.out.println(args[0] + " Has been split into " + args[1]
+ " pieces. " + "\n" + "Each file containig " + partSize
+ " Bytes each.");
}
}
答案 0 :(得分:1)