gpt4 book ai didi

java - 获取读取文件的进度

转载 作者:行者123 更新时间:2023-12-01 12:45:01 24 4
gpt4 key购买 nike

这是我的java代码的一部分,我想获取从文件读取的字节数,我在每个循环周期中增加4个字节,因为整数的大小是4个字节,但是这段代码无法正常工作,该代码的循环运行超出了文件的大小。请解决问题。

import java.io.File;
import java.util.Scanner;



public class S {


public S() throws Exception {

Scanner sc = new Scanner(new File("file.txt"));

for(int i=0; sc.hasNext(); i+=4) {
sc.nextInt();
System.out.println("Read = "+i+" bytes");
}

System.out.println("done");
}


public static void main(String arg[]) throws Exception {
new S();
}

}

最佳答案

扫描仪不是为此类用例而设计的。扫描仪将读取比当前使用的更多的数据 - 如果您跟踪写入的字节,您将获得预期的其他结果:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;



public class S {


private final static class ProgressStream extends FileInputStream {
private int bytesRead;

private ProgressStream(File file) throws FileNotFoundException {
super(file);
}

@Override
public int read() throws IOException {
int b = super.read();
if (b != -1)
bytesRead++;
return b;
}

@Override
public int read(byte[] b) throws IOException {
int read = super.read(b);
if (read != -1)
bytesRead += read;
return read;
}

@Override
public int read(byte[] b, int off, int len) throws IOException {
int read = super.read(b, off, len);
if (read != -1)
bytesRead += read;
return read;
}
}

public S() throws Exception {

ProgressStream progressStream = new ProgressStream(new File("file.txt"));

Scanner sc = new Scanner(progressStream);

while (sc.hasNext()) {
sc.nextInt();
System.out.println("Read = " + progressStream.bytesRead + " bytes");
}

System.out.println("done");
}


public static void main(String arg[]) throws Exception {
new S();
}

}

对于输入文件

123 456   789

输出

Read = 13 bytes
Read = 13 bytes
Read = 13 bytes
done
<小时/>

因此,您必须自己实现类似扫描仪的功能...

import java.io.File;
import java.io.FileInputStream;



public class S {

public S() throws Exception {

FileInputStream stream = new FileInputStream(new File("file.txt"));

int b;
StringBuilder lastDigits = new StringBuilder();
int read = 0;
while ((b = stream.read()) != -1) {
read++;
char c = (char) b;
if (Character.isDigit(c)) {
lastDigits.append(c);
} else if (lastDigits.length() > 0) {
System.out.println("found int "+Integer.parseInt(lastDigits.toString()));
System.out.println("Read = "+read+" bytes");
lastDigits = new StringBuilder();
}
}

if (lastDigits.length() > 0) {
System.out.println("found int "+Integer.parseInt(lastDigits.toString()));
System.out.println("Read = "+read+" bytes");
}

System.out.println("done");
}


public static void main(String arg[]) throws Exception {
new S();
}

}

将输出

found int 123
Read = 4 bytes
found int 456
Read = 8 bytes
found int 789
Read = 13 bytes
done

关于java - 获取读取文件的进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24791073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com