2014-10-20 42 views
0

我有这样的代码:快速的方法来读取特定数据的Java

System.setIn(new FileInputStream(System.getProperty("user.dir") + "/src/one.in")); 
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 

for (i = 0; i < ...; i++) { 
     String line = reader.readLine(); 
     String firstLocation = line.substring(0, line.indexOf(' ')); 
     String mid = line.substring(line.indexOf(' '), line.lastIndexOf(' ')).trim(); 
     String secondLocation = line.substring(line.lastIndexOf(' ') + 1); 
     .... 
} 

和我读到形式的多行:

A --875-> B 
A <-854-- B 
A --713-> B 
A <-908-- B 
A --925-> B 
A <-894-- B 
A --239-> B 
A <-30-- B 
A --802-> B 

是否有读取最快的方式并处理此线?我也尝试阅读所有行,并使用行尾字符进行分割,但它的工作速度更慢。

+0

我可能会使用'line.split(“”)',但问题是如果你在做任何其他可能导致缓慢的循环。 – RealSkeptic 2014-10-20 09:25:28

回答

0
String[] parts = line.split(" "); 
String firstLocation = parts[0]; 
String mid = parts[1]; 
String secondLocation = parts[2]; 
1

我知道的最快的方法是使用StringTokenizer。然后,你的代码应该是这样的:

System.setIn(new FileInputStream(System.getProperty("user.dir") "/src/one.in")); 
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 

while (reader.ready()) { 
    final StringTokenizer tk = new StringTokenizer(reader.readLine()," "); 
    String first = tk.nextToken(); 
    String second = tk.nextToken(); 
    String third = tk.nextToken(); 
    ... 
} 

我就不会在这里检查是否有足够的令牌可用,beause你知道你输入的字符串,这也节省了时间的次结构。如您所见,here StringTokenizer比使用Patternsplit(...)方法更快。

+0

来自文档:“StringTokenizer是一个遗留类,由于兼容性原因而保留,尽管在新代码中不鼓励使用它。建议任何寻求此功能的人都使用String的拆分方法或java.util.regex包。 “ – weston 2014-10-20 09:31:30

+0

这是真的,但他要求的性能不是兼容性:-) – Westranger 2014-10-20 09:35:02

+0

但+1在找到类似情况下更快的证据。 – weston 2014-10-20 09:49:58

0

如果你设计你的方法并将它保存为一个库(甚至作为一个IDE的模板!) 例如,如果你想从System.in中读取整数,你可以使用这个函数

static int readInt(BufferedInputStream b) throws IOException { 
    String s = ""; 
    int x = b.read(); 
    while (x < 48 || x > 57) { 
     x = b.read(); 
    } 
    while (x >= 48 && x <= 57) { 
     s = s + (char) x; 
     x = b.read(); 
    } 
    return Integer.parseInt(s); 
} 

这种方法会在输入中读取下一个可用的整数。 此方法忽略任何非数字字符。

例如,如果你输入的是这样的:

" 123 [email protected]@b" 

输出将独自

123 

最重要的部分是,这种方法确实在扫描仪,但方式nextInt()的作用比前者快。