[英]How to get total number of lines in a file in linux using java
我正在嘗試使用Runtime.getRuntime().exec(command)
運行wc -l filename
命令並獲取總行數。 但這是行不通的。
這是我的代碼:
private String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
System.out.println(command);
p = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line.split("\\s+")[0] + "\n");
}
int exc = p.waitFor();
System.out.println(exc);
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
exc
(出口值)為零。 當我打印要傳遞的命令時,它會給出正確的命令。 我也嘗試過復制該命令並在Linux中運行它。 它正在工作,但不是通過程序。
我要傳遞給functionexecuteCommand中的命令變量的命令是:wc -l <log1
它包含大約4597110的總行數。而且我也不想以字節為單位的文件大小,我只需要獲取總行數。
一種更簡單的替代方法(使用Java 8)。
long lines = Files.lines(Paths.get("foo.txt")).count();
如果您使用的是Java 8或更高版本,那么Kayaman的答案會更好。 但是,如果您停留在較早的迭代中,請參見下文。
您會看到這段代碼,用於評估wc
的輸出:
while ((line = reader.readLine())!= null) {
output.append(line.split("\\s+")[0] + "\n");
}
這與可以直接讀取文件並計算行數的代碼非常相似。
因此,我不確定您為什么認為需要調用外部程序來執行此任務, 尤其是因為它會降低代碼的可移植性。
只需打開文件並閱讀各行,然后為每行添加一個即可。 在那兒,行數就可以了。
例如,請參閱以下文件:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
public class Test
{
static private int getLineCount(String fspec) {
String line;
int count = 0;
try {
BufferedReader reader = new BufferedReader(
new FileReader(new File(fspec)));
while ((line = reader.readLine())!= null)
count++;
} catch (Exception e) {
count = -1;
}
return count;
}
public static void main(String[] args) {
System.out.println (getLineCount("/tmp/tempfile"));
}
}
運行它得到140
就像wc -l
的輸出一樣:
pax> wc -l /tmp/tempfile
140 /tmp/tempfile
看起來您沒有傳遞正確的文件路徑,請在運行方法時嘗試執行以下操作:
URL fileName = ClassLoader.getSystemClassLoader().getResource("filename");
System.out.println(executeCommand("wc -l " + fileName.getPath()));
嘗試通過以下方式使用Process
:
ProcessBuilder pb = new ProcessBuilder("wc", "-l");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));){
Process process = pb.start();
while (reader.readLine() != null){
// you need to figure out in which line the
// relevant output is and parse that to int
// just look at some sample outputs of wc -l
}
int err = process.waitFor();
if(err!=0) {
// your code for processing the number of lines goes here
// the command finished without error
}
else {
// your code here in case the command had an error
}
} catch (Exception e){
// catch an Exception like IOException or InterruptedException here
}
基本上, Reader
將從命令中讀取輸出,該輸出將在在那里執行命令時進入終端。
您可以使用apache common io FileUtils.readLines(文件文件)
FileUtils.readLines(new File("filename.txt")).size()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.