我想通过使用二进制流来显示复制文件时的百分比,但我不知道方法,那该怎么做?
以下是我的代码。
public static void binaryStream() throws IOException {
try {
FileInputStream inputStream = new FileInputStream(new File("Untitled.png"));
FileOutputStream outputStream = new FileOutputStream(new File("Untitled-copied.png"));
int data;
while ((data = inputStream.read()) >= 0) {
outputStream.write(data);
}
outputStream.write(data);
inputStream.close();
outputStream.close();
} catch (FileNotFoundException e) {
System.out.println("Error");
} catch (IOException e) {
System.out.println("Error");
}
}
答案 0 :(得分:0)
如何像评论中提到的其他人那样做的例子。
import java.io.*;
public class BinaryStream {
public static void binaryStream(String file1, String file2) throws Exception
{
File sourceFile = new File(file1);
try(
FileInputStream inputStream = new FileInputStream(sourceFile);
FileOutputStream outputStream = new FileOutputStream(new File(file2))
) {
long lenOfFile = sourceFile.length();
long currentBytesWritten = 0;
int data;
while ((data = inputStream.read()) != -1) {
outputStream.write(data);
currentBytesWritten += 1;
System.out.printf("%2.2f%%%n",
100*((double)currentBytesWritten)/((double)lenOfFile));
}
}
}
public static void main(String args[]) throws Exception {
binaryStream("Untitled.png", "Untitled-copied.png");
}
}
请注意,我做了一些更改:
-1
比较,因为这是文件结尾的记录值(流结束)在我的电脑上输出是这样的:
0,06%
// removed data
99,89%
99,94%
100,00%
另请注意,此代码将在每个字节写入后打印一些内容,因此高度效率低下。您可能希望不那么经常这样做。在这方面,你一次只读取和写入一个字节,这也是非常低效的 - 你可能想要使用read(byte[])而不是读取块。例如,使用256字节数组:
import java.io.*;
public class BinaryStream {
public static void binaryStream(String file1, String file2) throws Exception {
File sourceFile = new File(file1);
try(
FileInputStream inputStream = new FileInputStream(sourceFile);
FileOutputStream outputStream = new FileOutputStream(new File(file2))
) {
long lenOfFile = sourceFile.length();
long bytesWritten = 0;
int amountOfBytesRead;
byte[] bytes = new byte[256];
while ((amountOfBytesRead = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, amountOfBytesRead);
bytesWritten += amountOfBytesRead;
System.out.printf("%2.2f%%%n",
100*((double)bytesWritten)/((double)lenOfFile));
}
}
}
public static void main(String args[]) throws Exception {
binaryStream("Untitled.png", "Untitled-copied.png");
}
}
我的电脑输出:
14,69%
29,37%
44,06%
58,75%
73,44%
88,12%
100,00%
请注意,在第一个示例中,.read()的返回值实际上是读取的字节,而在第二个示例中,.read()的返回值是字节的 amount 读取并且实际字节进入字节数组。