【问题标题】:How to Get a value from a text file如何从文本文件中获取值
【发布时间】:2015-03-18 13:08:37
【问题描述】:

我的问题:我需要从一个文本文件中获取多个值。

我正在研究从 ttcn-3 语言到 XML 语言的解析器,我需要做的是从 ttcn 模块中获取一些关键词和值,这些模块写在文本文件中以构建 XML 文件。

这是我的 ttcn 代码的开始:

module SessionSetup
{
type port InputPortType message { in charstring }
type port OutputPortType message { out charstring }
type component SessionSetupResComponentType {
    port InputPortType InputPort;
    port OutputPortType OutputPort;
}

例如,我需要获取模块 (SessionSetup) 之后的字符串,这是我制作的代码:

public  void ReadTheFileGetTheModuleName(String fichier){
            try{
                InputStream ips=new FileInputStream(fichier); 
                InputStreamReader ipsr=new InputStreamReader(ips);
                BufferedReader br=new BufferedReader(ipsr);
                String ligne;

                while ((ligne=br.readLine())!=null){
                    if (ligne.contains("module"))
                    {
                        String[] st = ligne.split(ligne, ' ');
                        System.out.println("Nom = "+st[1]);
                    }

                    chaine+=ligne+"\n";

                }
                br.close();
            }       
            catch (Exception e){
                System.out.println(e.toString());
            }
        }

问题是它不起作用,我没有得到模块后的字符串。

谢谢

【问题讨论】:

  • 或许可以尝试用 Scanner 来做,这不是最快的方法,但真的很简单
  • 你在下一行读到什么?我认为你必须在你的 while 循环中添加 ligne=br.readLine(); 并且要获得不是 NPE 我会设置 ligne=""; 而不是 split,尝试使用 substring

标签: java string file text-files


【解决方案1】:
 String[] st = ligne.split(ligne, ' ');
                       /\/\/\/\/\/\/\
                 Incorrect way, pass some regex on which string should split

您的String#Split()方法错误,请检查documentation

应该是这样的

public String[] split(String regex, int limit)

or

public String[] split(String regex)

注意:不会出现编译时错误,因为 split() 方法中的 this (' ') 是一个字符,可以隐式类型转换为 Integer。

【讨论】:

    猜你喜欢
    • 2018-01-09
    • 2015-01-14
    • 2023-04-01
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多