在Java中拆分字符串
我正在使用javaexec命令发出“hcitool scan”命令以执行蓝牙扫描 输出的格式与我向终端输入命令时的格式完全相同在Java中拆分字符串,java,Java,我正在使用javaexec命令发出“hcitool scan”命令以执行蓝牙扫描 输出的格式与我向终端输入命令时的格式完全相同 scanning... mac address bluetoothName Done 我希望能够拆分返回的字符串,以便将找到的MAC地址存储为字符串 我的代码如下: import java.io.*; public class altBluetooth { public static void main(String args[]) { t
scanning...
mac address bluetoothName
Done
我希望能够拆分返回的字符串,以便将找到的MAC地址存储为字符串
我的代码如下:
import java.io.*;
public class altBluetooth
{
public static void main(String args[])
{
try
{
Process p=Runtime.getRuntime().exec("hcitool scan");
p.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line!=null)
{
System.out.println(line);
line=reader.readLine();
}
}
catch(IOException e1) {
System.out.print("This didnt work - exception 1");
}
catch(InterruptedException e2) {
System.out.print("This didnt work - exception 2");
}
System.out.println("Done");
}
}
可能如果您需要高级拆分,您可以使用中的
com.google.common.base.Splitter
。你知道String
有一个方法,对吗?别偷懒了,自己动手做吧。你有关于这些行的确切输出的更多细节吗?它们是以制表符分隔的吗?只是空间?任何字段中都可以有空格吗?String.split()
应该可以。您可能想了解正则表达式。我还建议您熟悉Java文档,或是一本很棒的书《用Java思考》。这里介绍了基本内容(以及更多内容)。请注意,如果不立即开始读取输出,p.waitFor()可能永远不会完成。如果hcitool扫描的输出太大,操作系统的内部输出缓冲区可能会阻塞!输出以制表符分隔-我想放弃蓝牙名称,只存储MAC地址。我将试着给出答案。
String[] parts = line.split("\\s+");