Java 未被正则表达式删除的空行
我正在读取shell输出并将其显示到控制台。我正在改变Java 未被正则表达式删除的空行,java,linux,command-line,output,Java,Linux,Command Line,Output,我正在读取shell输出并将其显示到控制台。我正在改变 行 与 String test=line.replaceAll(“[\\\r\\\n]+”,”) 我认为应该删除所有空行,但输出不会改变 public class tempapp{ public static void main(String[] args) throws IOException, InterruptedException { String fileName = "temps.txt";
行
与
String test=line.replaceAll(“[\\\r\\\n]+”,”)代码>
我认为应该删除所有空行,但输出不会改变
public class tempapp{
public static void main(String[] args) throws IOException, InterruptedException {
String fileName = "temps.txt";
TimerTask task = new TimerTask() {
@Override
public void run(){
// task goes here
List<String> commands = new ArrayList<>();
//build command
commands.add("/usr/bin/sensors");
//args
//commands.add("");
System.out.println(commands);
ProcessBuilder pb = new ProcessBuilder(commands);
pb.directory(new File("/home/ethano"));
pb.redirectErrorStream(true);
Process process = null;
try {
process = pb.start();
} catch (IOException e) {
e.printStackTrace();
}
//Read output
StringBuilder out = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null, previous = null;
while (true) {
try {
if (!((line = br.readLine()) != null)) break;
} catch (IOException e) {
e.printStackTrace();
}
if (!line.equals(previous)) {
previous = line;
out.append(line).append('\n');
String test = line.replaceAll("[\\\r\\\n]+","");
System.out.println(test);
}
}
//Check result
try {
if (process.waitFor() == 0) {
//System.exit(0);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
//weird termination
//System.err.println(commands);
//System.err.println(out.toString());
//System.exit(1);
}
};
Timer timer = new Timer();
long delay = 0;
long intervalPeriod = 4 * 1000;
//schedules task to run in interval
timer.scheduleAtFixedRate(task, delay, intervalPeriod);
}
}
公共类tempapp{
公共静态void main(字符串[]args)引发IOException、InterruptedException{
字符串fileName=“temps.txt”;
TimerTask任务=新的TimerTask(){
@凌驾
公开募捐{
//任务就在这里
List命令=new ArrayList();
//生成命令
添加(“/usr/bin/sensors”);
//args
//命令。添加(“”);
System.out.println(命令);
ProcessBuilder pb=新的ProcessBuilder(命令);
目录(新文件(“/home/ethano”);
pb.重定向错误流(真);
Process=null;
试一试{
process=pb.start();
}捕获(IOE异常){
e、 printStackTrace();
}
//读取输出
StringBuilder out=新的StringBuilder();
BufferedReader br=新的BufferedReader(新的InputStreamReader(process.getInputStream());
String line=null,previous=null;
while(true){
试一试{
如果(!((line=br.readLine())!=null))中断;
}捕获(IOE异常){
e、 printStackTrace();
}
如果(!line.equals(上一个)){
上一个=行;
out.append(line.append('\n');
字符串测试=行.replaceAll(“[\\\r\\\n]+”,“”);
系统输出打印LN(测试);
}
}
//检查结果
试一试{
if(process.waitFor()==0){
//系统出口(0);
}
}捕捉(中断异常e){
e、 printStackTrace();
}
//奇怪的终止
//System.err.println(命令);
//System.err.println(out.toString());
//系统出口(1);
}
};
定时器=新定时器();
长延时=0;
长间隔期=4*1000;
//计划任务以间隔运行
timer.scheduleAtFixedRate(任务、延迟、间隔期);
}
}
regex应该是(“[\\r\\n]+”,”)代码>字符串中只有一行没有行终止符。如果不想将字符串写入文件,则应选中If(line.isEmpty())