[英]Reading a particular line from a text file in Java
What is the most efficient way to extract specific line numbers of data from a text file? 从文本文件中提取特定行数的最有效方法是什么? For example, if I use the Scanner to parse a file, do I first have to create an array with a length matching the total number of lines in the text file?
例如,如果我使用扫描仪来解析文件,我是否首先要创建一个长度与文本文件中的总行数相匹配的数组?
If a text file has 30 lines and I only want to work with lines 3, 8, and 12, is there a way to specifically only read those lines? 如果一个文本文件有30行,我只想使用第3,第8和第12行,有没有办法专门只读取这些行?
here is how you do it: 这是你如何做到的:
import java.io.*;
public class Test {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "temp.txt";
int counter = 0;
// This will reference one line at a time
String line = null;
FileReader fileReader = null;
try {
// FileReader reads text files in the default encoding.
fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
counter++;
if(counter == 3 || counter == 8 || counter == 12)
{
// do your code
}
}
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
finally
{
if(fileReader != null){
// Always close files.
bufferedReader.close();
}
}
}
}
here is what you can do. 这是你能做的。 (it is only part of your program, not exactly your program)
(它只是你程序的一部分,不完全是你的程序)
int counter 0 =;
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// process the line.
counter++;
switch(counter){
case 3:
\\ do your code for line no 3
break;
case 8:
\\ do your code for line no 8
break;
case 12:
\\ do your code for line no 12
break;
}
}
br.close();
Try this 试试这个
try
{
String sCurrentLine;
br = new BufferedReader(new FileReader("File_Path"));
int counter = 0;
while ((sCurrentLine = br.readLine()) != null)
{
counter++;
if (counter == 3 || counter == 8 || counter == 12)
{
System.out.println("" + br.read());
if (counter == 12)
break;
}
}
}
catch (IOException e)
{
System.out.println("Exception " + e);
}
finally
{
try
{
if (br != null)
{
br.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
here you can find the the solution for reading a file according to the line no. 在这里你可以找到根据行号读取文件的解决方案。 This site is the best It contain this code in all the programming languages.
这个站点是最好的它包含所有编程语言中的代码。 And I have given you the java code.
而且我已经给你了java代码。
https://www.rosettacode.org/wiki/Read_a_specific_line_from_a_file#Java https://www.rosettacode.org/wiki/Read_a_specific_line_from_a_file#Java
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.