【问题标题】:Get specific text from a .txt file从 .txt 文件中获取特定文本
【发布时间】:2023-08-27 14:38:01
【问题描述】:

我想从脚本中获取信息,所以我使用了这个函数

public static HashMap<String, String> getEnvVariables(String scriptFile,String config) {
    HashMap<String, String> vars = new HashMap<String, String>();
    try {

        FileInputStream fstream = new FileInputStream(scriptFile);
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
        String strLine;
                          String var= "if [ \"$1\" = \""+config +"\" ] ; then";
        // Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            // use a Scanner to parse the content of each line
            // exclude concatenated variables (export xx:$xx)
            if (strLine.startsWith("export") && !strLine.contains("$")) {
                strLine = strLine.substring(7);
                Scanner scanner = new Scanner(strLine);
                scanner.useDelimiter("=");
                if (scanner.hasNext()) {
                    String name = scanner.next();
                    String value = scanner.next();
                    System.out.println(name+"="+value);
                    vars.put(name, value);
                }
            }
        }

但是我想从特定的行开始阅读

if [ \"$1\" = \""+config +"\" ] ; then

问题是当一行以空格开头时,程序认为文件已经结束! 那么我该如何修复它并使程序解析到文件末尾? 考虑到该行可能以多个空格开头 谢谢

【问题讨论】:

    标签: java bufferedreader fileinputstream


    【解决方案1】:

    你可以尝试从每一行修剪不相关的空格?

    while ((strLine = br.readLine().trim()) != null) {...}
    

    编辑:不要那样做(感谢 Joop Eggen!),否则你会有一个不错的 NPE ......)。试试:

    while ((strLine = br.readLine()) != null) {
        strLine = strLine.trim();
        ...
    }
    

    【讨论】:

    • 好主意,人们经常忘记简单的.trim()。尽管在{ ... } 内执行此操作,因为您还没有测试 strLine 是否为空。
    • 仅在行首只有一个空格时有效:
    • @Rad1 “有效”是什么意思?它也适用于多个空间。这就是trim() 的用途。
    • 根据documentation 修剪适用于多个字符,而不仅仅是空格字符。 @Rad1 可能是您的意思是高效,这取决于实现。
    • @Zhedar 我的意思是当缓冲区正在读取文件时,如果该行以一个空格开始它读取它,则修剪,当超过一个空格时它认为文件结束并退出!跨度>
    【解决方案2】:

    听起来你应该使用正则表达式(例如使用String.matches() 方法)。他们还可以提取字符串或子字符串(参见:another * article)。

    Lars Vogella 还对 Java 中的 regular expressions 做了出色的介绍。 Oracle 还编译了一个关于该主题的Tutorial/Lesson

    可能这个 sn-p 有点帮助(使用org.apache.commons.io.LineIterator):

    public void grepLine(File file, String regex)
    {
        LineIterator it = FileUtils.lineIterator(file, "UTF-8");
        try
        {
            while (it.hasNext())
            {
                String line = it.nextLine();
                if(line.matches(regex))
                {
                        //...do your stuff
                }
            }
        }
        finally
        {
            LineIterator.closeQuietly(it);
        }
    }
    

    正则表达式可能类似于(注意:尚未检查 - 尤其是反斜杠):

    String regex="^\\s*if\\s+\\[\\s+\\\"\\$1\\\" = \\\""+config +"\\\" \\] ; then";
    

    【讨论】:

      【解决方案3】:

      首先:省略 DataInputStream,更多 Java 对象特定。

      boolean started = false;
      while ...
          if (!started) {
              started = strLine.matches("\\s*...\\s*");
          } else {
              ...
      

      Reg ex \\s* 代表零个或多个空白字符(制表符、空格)。

      【讨论】:

        【解决方案4】:

        我找到了一个解决方案,分享给大家。

        public static HashMap<String, String> getEnvVariables(String scriptFile ,String config1,String config2) {
            HashMap<String, String> vars = new HashMap<String, String>();
            BufferedReader br = null;
            try {
                FileInputStream fstream = new FileInputStream(scriptFile);
                br = new BufferedReader(new InputStreamReader(fstream));
                String strLine = null;
                String stopvar = config2;
                String startvar =config1;
                String keyword = "set";
                do {
                    if (strLine != null && strLine.contains(startvar)) {
                        if (strLine.contains(stopvar)) {
                            return vars;
                        }
                        while (strLine != null && !strLine.contains(stopvar)) {
                            strLine = br.readLine();
                            if (strLine.trim().startsWith(keyword)&& !strLine.contains("$")) {
                                strLine = strLine.trim().substring(keyword.length())
                                .trim();
                                String[] split = strLine.split("=");
                                String name = split[0];
                                String value = split[1];
                                System.out.println(name + "=" + value);
                                vars.put(name, value);
                            }
                        }
                    }
                } while ((strLine = br.readLine()) != null);
            } catch (Exception e) {
                Status status = new Status(Status.ERROR, Activator.PLUGIN_ID,
                        IStatus.ERROR, e.getMessage(), e);
                Activator.getDefault().getLog().log(status);
            }
            return vars;
        }
        

        感谢您的帮助!

        【讨论】: