简体   繁体   English

如何在文件中搜索名称并提取值

[英]How to search for name in file and extract value

I have a file that looks like this: 我有一个看起来像这样的文件:

Dwarf remains:0
Toolkit:1
Cannonball:2
Nulodion's notes:3
Ammo mould:4
Instruction manual:5
Cannon base:6
Cannon base noted:7
Cannon stand:8
Cannon stand noted:9
Cannon barrels:10
... 

What is the easiest way to open this file, search for name and return the value of the field? 打开此文件,搜索名称并返回字段值的最简单方法是什么? I cannot use any external libraries. 我不能使用任何外部库。

What i have tried/is this ok? 我尝试过的/可以吗?

    public String item(String name) throws IOException{
    String line;
    FileReader in = new FileReader("C:/test.txt");
    BufferedReader br = new BufferedReader(in);


    while ((line = br.readLine()) != null) {
        if(line.contains(name)){
            String[] parts = line.split(":");
            return parts[1];
        }
    }

    return null;



}

The task can be easily achieved using basic Java capabilities. 使用基本的Java功能可以轻松完成此任务。 Firstly, you need to open the the file and read its lines. 首先,您需要打开文件并阅读其行。 It can be easily achieved with Files.lines (Path.get ("path/to/file")) . 可以通过Files.lines (Path.get ("path/to/file"))轻松实现。 Secondly, you need to iterate through all the lines returned by those instructions. 其次,您需要遍历这些指令返回的所有行。 If you do not know stream API, you can change value returned from Files.lines (...) from Stream to an array using String[] lines = Files.lines(Paths.get("path/to/file")).toArray(a -> new String[a]); 如果您不知道流API,则可以使用String[] lines = Files.lines(Paths.get("path/to/file")).toArray(a -> new String[a]);将从Files.lines (...)返回的值从Stream更改为数组。 String[] lines = Files.lines(Paths.get("path/to/file")).toArray(a -> new String[a]); . Now lines variable has all the lines from the input file. 现在lines变量具有输入文件中的所有行。

You have to then split each line into two parts ( String.split ) and see whether first part equals ( String.equals ) what you're looking for. 然后,您必须将每一行分成两部分( String.split ),然后查看第一部分是否等于( String.equals )您要查找的内容。 Then simply return the second one. 然后只需返回第二个。

As a followup to your code - it compiles and works ok. 作为代码的后续步骤-它可以编译并正常运行。 Be aware though, that / is not the correct path separator on Windows ( \\ is). 但是请注意, /不是Windows上正确的路径分隔符( \\是)。 You could've created the correct path using, for example: Paths.get("C:", "test.txt").toString() . 您可以使用以下示例创建正确的路径: Paths.get("C:", "test.txt").toString() Correct separator is defined as well in File.separator . File.separator也定义了正确的分隔符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM