我必须读取一个文件,并且根据最后几行的内容,我必须将其大部分内容复制到一个新文件中。不幸的是,我没有找到一种方法来复制 java 中文件的前 n 行或字符。
我发现的唯一方法是使用 nio FileChannels 复制文件,我可以在其中指定长度(以字节为单位)。但是,因此我需要知道我读取的内容在源文件中需要多少字节。
有谁知道这些问题的解决方案吗?
最佳答案
试试这个:
Scanner scanner = new Scanner(yourFileObject); // initialise scanner
然后
for (int i = 0; i < amountOfLines; i++) {
String line = scanner.nextLine(); // get line excluding \n at the end
// handle here
}
OR,对于 n 字符,而不是行:
Pattern charPattern = Pattern.compile(".")
// java.util.regex.Pattern with any char allowed
for (int i = 0; i < amountOfChars; i++) {
char next = scanner.next(charPattern).toCharArray()[0];
// handle here
}
在我看来,这是迄今为止从文件中获取前 n 个字符/行的最佳且最容易编写的方法。
关于Java如何复制文件的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25168907/