import java.io.*;
class SplitFile
{
private File fSplit;
private int sizeInBytes;
private int count;
public static void main(String[] args) throws IOException
{
Console con = System.console();
String fileName;
int size = 0;
System.out.print("Enter the file name to split: ");
fileName = con.readLine();
System.out.print("Enter the size of the target file: ");
size = Integer.parseInt(con.readLine());
SplitFile sf = new SplitFile(fileName, size);
sf.split();
}
public File checkFileExists(String fName)
{
File f = new File(fName);
if (!f.exists())
{
System.out.println("File " + fName + " does not exists");
System.exit(0);
}
return f;
}
public int validateSize(int s)
{
if (fSplit.length() < s)
{
System.out.println("Invalid Size");
System.exit(0);
}
return s;
}
public String createNextFileName()
{
++count;
String fileName;
fileName = "part_" + count + "." + fSplit.getName();
return fileName;
}
public SplitFile(String fName, int s)
{
fSplit = checkFileExists(fName);
sizeInBytes = validateSize(s);
count = 0;
}
public void split() throws IOException
{
FileInputStream fis = new FileInputStream(fSplit);
BufferedInputStream bis = new BufferedInputStream(fis);
File fileSegment = new File(createNextFileName());
FileOutputStream fos = new FileOutputStream(fileSegment);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int ch;
int currentByteCount = 0;
while ((ch = bis.read()) != -1)
{
bos.write(ch);
++currentByteCount;
if (currentByteCount == sizeInBytes)
{
bos.close();
fos.close();
fileSegment = new File(createNextFileName());
fos = new FileOutputStream(fileSegment);
bos = new BufferedOutputStream(fos);
currentByteCount = 0;
}
}
bis.close();
fis.close();
bos.close();
fos.close();
}
}
基于文档
文件和目录路径名的抽象表示。
File
是一种引用类型。它用于处理文件(例如创建)通过查看这个链接,你会更容易理解它
更新
通过查看您对上一个答案的评论,我发现您不知道/不熟悉java中的不同数据类型,有两种数据类型。
- 基元数据类型(char、int、boolean)
- 引用类型/对象(用户定义的类,超类
Object
,在您的情况下File
)
文件Object只是一个用于处理文件的对象,您可以在此处阅读文档。