JAVA读取文件中的ip地址,依次长ping,将结果保存到不同的文件中。
打开IDEA,创建一个类,名字为AddThread
package com.Thread;
import java.io.*;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class AddThread{
public static void main(String args[]) throws IOException {
AddThread view = new AddThread();
FileReader fr = new FileReader("D:/IPAddress.txt");// 创建FileReader对象,用来读取字符流
BufferedReader br = new BufferedReader(fr); // 缓冲指定文件的输入
String myreadline; // 定义一个String类型的变量,用来每次读取一行
while (br.ready())
{
myreadline = br.readLine();// 读取一行
view.writerLog("C:\\","ping "+myreadline+" -t",myreadline);//测试通过读取的ip生成文件
}
}
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public void writerLog(final String cmdpath, final String cmd,String IPAdress) throws IOException {
File logFile = new File("D:/Result/"+IPAdress+".log");// 创建FileWriter对象,用来写入字符流
File dir = new File(cmdpath);
if(!logFile.exists()) {
logFile.createNewFile();
}
//启动一个线程每2秒钟向日志文件写一次数据
ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
exec.scheduleWithFixedDelay(new Runnable(){
public void run() {
try {
Process ps = Runtime.getRuntime().exec(cmd, null, dir);
BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream(), Charset.forName("GBK")));
String line = null;
//FileWriter fw = new FileWriter("D:/Result/"+cmd+".txt",true);
//BufferedWriter bw = new BufferedWriter(fw);// 将缓冲对文件的输出
if(logFile == null) {
throw new IllegalStateException("logFile can not be null!");
}
while ((line = br.readLine()) != null) {
System.out.println(line);
Writer txtWriter = new FileWriter(logFile,true);
txtWriter.write(dateFormat.format(new Date()) +"\t"+ line +"\n");
txtWriter.flush();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}, 0, 2, TimeUnit.SECONDS);
}
}