java - 获取给定字符串的值

标签 java

我想搜索一个字符串并在文件中获取该字符串的值。 例如文件包含这样的内容

test=1

test2=2

如果给出搜索字符串 str="test2"那么它应该返回值 2 。 我尝试过的示例代码是

public class ScannerExample {

    public static void main(String args[]) throws FileNotFoundException {
 
        //creating File instance to reference text file in Java
        
        String filePath = "c:/temp/test.txt";
        //Creating Scanner instnace to read File in Java
        
        String str = "text";
        //Reading each line of file using Scanner class
        BufferedReader br = new BufferedReader(new FileReader(filePath));
        String sCurrentLine;
        while ((sCurrentLine = br.readLine()) != null) {
            if(sCurrentLine.contains(str))  {
                result=true;
                System.out.println("Found entry ");
                break;
            }
        }
    }  
}

这里我检查值是否存在。请建议一些方法来获取它的值

sample.txt:
test=1
test2=2
testnew=new
testold=old2

最佳答案

只需使用 Properties 对象并用它加载文件

Properties p = new Properties();
try (Reader reader = new FileReader(filePath)) {
    // Load the file
    p.load(reader);
}
// Print the value of the parameter test2
System.out.println(p.getProperty("test2"));

关于java - 获取给定字符串的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37967379/

相关文章:

java - 如何在 super.xxx() 之后使用 Javassist 插入代码

c# - 存在哪些开源空间索引库?

java - 保留随机 UUID 作为 JPA 实体上的对象 ID?

java - 文件上传zuul代理请求大小问题

c# - 使用 Java 在 C# 中从嵌套类访问父类成员的差异

java - ClassCastException 与 JAXB - Websphere jar 与 applicationl jar

java.sql.SQLException : Column not found Error?

java.io.FileNotFoundException/employee.xml : open failed ENOENT (No such file or directory) on file read

java - 如何解决java.util.NoSuchElementException?

java - 在Android中正确测试静态方法