[英]How to get a value in a file with coordinates in Java
My programm needs to read a file that has different data structures with a variable separator.我的程序需要读取一个具有可变分隔符的不同数据结构的文件。 In my properties-file you can set the separator and put coordinates for values of different variables:在我的属性文件中,您可以设置分隔符并为不同变量的值放置坐标:
separator = ;
variable1 = 1,7
variable2 = 2,42
I would like to have a way where I can access a column and a line with some kind of coordinates.我想有一种方法可以访问具有某种坐标的列和线。
I'm thinking of a syntax like this:我正在考虑这样的语法:
file.get(1,7,";")
(Which would give you the value of the 1st line and 7th column with the specific separator) Does someone know a library or a code snippet that does exactly this? (哪个会给你带有特定分隔符的第一行和第七列的值)有人知道一个库或一个代码片段吗?
Using String.split()
:使用String.split()
:
public String get(File file, int lineNumber, int column, String separator ) {
//getting to the lineNumber of the file ommitted
// suppose you got it in a String named "line"
return line.split(separator)[column - 1];
}
You can use OpenCSV or SuperCSV for example.例如,您可以使用OpenCSV或SuperCSV 。 I'm not aware of any library that does your 'coordinates' gettings, but it's as simple as reading the CSV with the given separator as List
-of- List
s and then call我不知道有任何库可以获取您的“坐标”,但这就像读取带有给定分隔符的 CSV 一样简单List
-of- List
s 然后调用
csv.get(1).get(7)
Seems to be a simple file processing, You should first process the file -看似简单的文件处理,你应该先处理文件——
ArrayList<ArrayList<String>>
processedFile创建ArrayList<ArrayList<String>>
处理文件"line".split(separator)
读取每一行,使用"line".split(separator)
分割"line".split(separator)
Once processedFile is ready, you can simply use processedFile.get(row).get(column)
.一旦processedFile准备好,您可以简单地使用processedFile.get(row).get(column)
。 Also once the file is processed, all the other queries will be O(1) .此外,一旦文件被处理,所有其他查询都将是O(1) 。 Hints are enough, try writing the code yourself, you will learn more.提示就够了,尝试自己写代码,你会学到更多。
PS: Take care of NullPointerExceptions
wherever required. PS:在需要的地方处理NullPointerExceptions
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.