[英]How to read file line by line to an array in Java skipping first int?
我试图读取Java中的文件并将其存储到数组中。 现在的问题是该文件具有以下结构。 我将在下面给出2个示例文件:
输入文件结构
<number of lines>
<line number> <value>
.
.
.
<line number> <value>
input1.txt
5
1 34
2 19
3 43
4 62
5 36
input2.txt
4
1 10.3430423
2 -34.234923
3 -100.39292
4 22
如您所见,文件以行数开头(例如4或5)。 在普通输入文本中,我有超过100000行。
因此,我的代码基本上可以获取用户输入,打开文件,创建数组大小和该大小的数组。 现在,我继续阅读下一行并将值添加到我的elements
数组中。 行号不应添加到数组中。 现在您可以看到,我的elements数组被声明为String。 是否可以实际读取文件,获取值的类型并创建该类型的数组? 我认为可以节省从字符串到int或double或float的转换?
下面是我的代码:
public static void main(String args[]) throws NumberFormatException, IOException{
String inFile; //Input file name.
int filterSize; //Filter size (odd integer >= 3).
String outFile; //Output file name.
int arraySize;
String[] elements;
int index = 0;
//Scanner to take input file name, filter size and output file name.
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Enter your keyboard input as follows: <data file name> <filter size(odd int >= 3> <output file name>");
//Assigning values to variables.
inFile = keyboardInput.next();
filterSize = keyboardInput.nextInt();
outFile = keyboardInput.next();
//Reading file into array using BufferReader
BufferedReader fileInput = new BufferedReader(new FileReader(inFile));
arraySize = Integer.parseInt(fileInput.readLine()); //Get Array Size
elements = new String[arraySize];
while(fileInput.readLine() != null){
elements[index] = fileInput.readLine();
index += 1;
}
}
任何帮助表示赞赏。 谢谢。
尝试这样做:
Scanner sc = new Scanner(new File(inFile));
arraySize = sc.nextInt();
elements = new String[arraySize];
while(sc.hasNext())
{
sc.nextInt();
elements[index] = sc.next();
index += 1;
}
创建新的扫描仪后,无需任何转换即可读取整数,布尔值等。 因为您不需要当前编号的行,所以只需阅读该编号即可。 您无需将其保存在任何地方。 然后,下一个数字/字符串必须保存在elements[index]
。 而已
基于流:
Files.lines(pathToFile).skip(1) // skip the line counter. Don't trust input
.map(line -> line.replaceFirst("\\d+", "")) // remove digits at the start
.collect(Collectors.toList()); // collect it into a list
您仍然可以使用.toArray()
将其存储到数组中
但是实际上您应该使用try-with-resources
来做到这一点:
try (Stream<String> lines = Files.lines(pathToFile).skip(1)) {
elements = lines.map(line -> line.replaceFirst("\\d", "")).collect(Collectors.toList());
} catch (IOException e) {
// sensible handling...
}
阅读号码,切勿使用。
File file = new File("input1.txt");
Scanner in = new Scanner(file);
int lines = in.nextInt();
int []a = new int[lines];
for(int i = 0; i < lines; i++)
{
int fakeNumber = in.nextInt();//read it but never used it
a[i] = in.nextInt();
}
您也可以in#hasNextLine()
使用。
真正的问题是如何删除行号并获取其值。
double[] array = .... // initialize your array
int v = 0;
while(file.readLine() != null){
// your array
array[v++] = Double.parseDouble(file.readLine().split(" ")[1]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.