如何解析文本文件

huangapple go评论64阅读模式
英文:

How to parse text file

问题

demo.txt :<br/>
FD1,true,102400,4000,0.01,103,83.25 <br/>
FD0,false,102400,4000,0.01,103,83.25

我想访问每一行的第一个元素,然后从每一行中访问每个元素,并将其作为参数传递给函数createFogDevice来执行某些操作。
类似于 createFogDevice(FD1,true,1024,4000,0.01,103,83.25) 

有人可以帮忙编写这个代码吗?
英文:

demo.txt :<br/>
FD1,true,102400,4000,0.01,103,83.25 <br/>
FD0,false,102400,4000,0.01,103,83.25

I want to access each line 1st then from each line i want to access each element and pass this as parameter to a function createFogDevice to perform some action.
like createFogDevice(FD1,true,1024,4000,0.01,103,83.25)

Can anybody help how we can write code for this ?

答案1

得分: 1

        Scanner scanner = new Scanner(new File());

        while (scanner.hasNextLine()) {
            String currentLine = scanner.nextLine();

            String[] dataPoints = currentLine.split(",");

            String a = dataPoints[0];
            boolean b = Boolean.parseBoolean(dataPoints[1]);
            // ....
            createFogDevice(a, b, c/*...*/);
        }
英文:
    Scanner scanner = new Scanner(new File());

    while(scanner.hasNextLine()) {
        String currentLine = scanner.nextLine();

        String[] dataPoints = currentLine.split(&quot;,&quot;);

        String a = dataPoints[0];
        boolean b = Boolean.parseBoolean(dataPoints[1]);
        // ....
        createFogDevice(a,b,c/*...*/);
    }

答案2

得分: 0

尝试这个:

try (Stream<String> stream = Files.lines(Paths.get("demo.txt"))) {

    stream.forEach(ob -> createFogDevice(ob.split(",")));

} catch (IOException e) {
    e.printStackTrace();
}

另外,您可以修改createFogDevice() 方法以传递字符串数组作为参数:

private static void createFogDevice(String[] inputParams) {
    // 在这里编写您的代码
}
英文:

Try This :-

	try (Stream&lt;String&gt; stream = Files.lines(Paths.get(&quot;demo.txt&quot;))) {

		stream.forEach(ob-&gt;createFogDevice(ob.split(&quot;,&quot;)));

	} catch (IOException e) {
		e.printStackTrace();
	}

Also you can modify createFogDevice() method to pass Array of String as argument :-

private static void createFogDevice(String[] inputParams) {
	// your code goes here
}

huangapple
  • 本文由 发表于 2020年10月7日 13:43:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/64237882.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定