java批量读取txt文档中的ip地址,并将结果以txt文本输出

自己弄了一个“批量去ping txt文本中ip地址,并将结果以TXT文本格式输出”的小demo,可能有些地方不够完善,有需要修改的地方,大家一起交流交流呀!
其实输出的时候还可以以Excel文件格式输出。

把txt文本按照一定的格式排列就行了,用fileinputstream去读,然后读出来的东西,按照你定义的规则进行解析成字符数组,遍历数组去ping不同的ip。

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class test {
    public static void main(String[] args) {
        List<String> readlist=readIpList("D://ip.txt");
        StringBuilder sb = new StringBuilder();
        for (String s : readlist) {
            System.out.println("检查循环的ip:::"+s);
            sb =sb.append(ping(s));
        }
        System.out.println(sb);
        write("D://ip_result.txt",sb.toString());
    }

	//write是将结果写进TXT文档
    private static void write(String write_filepath,String result){
        try {
            FileOutputStream outputStream = new FileOutputStream(write_filepath);
            String ss = result;
            byte[] write = ss.getBytes("GBK");
            outputStream.write(write, 0, write.length);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

	//读txt文档中的ip地址
    private static List<String> readIpList(String read_filepath){
        String temp;
        File file =new File(read_filepath);
        List<String> readlist= new ArrayList<>();
        try {
            InputStreamReader read= new InputStreamReader(new FileInputStream(file),"GBK");
            BufferedReader reader = new BufferedReader(read);
            while((temp=reader.readLine())!=null &&!"".equals(temp)){
                readlist.add(temp);
            }
            read.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return readlist;
    }

	//ping地址
    private static String ping(String ipstr) {
        // 前缀根据自己需求调整
        String ins = "ping " + ipstr;
        String result = null;
        try {
            Process p = Runtime.getRuntime().exec(ins);
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream(), "GBK"));
            String line = null;
            StringBuilder sb = new StringBuilder();

            while ((line = reader.readLine()) != null) {
                sb=sb.append(line + "\n");
            }
            result =sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}

你可能感兴趣的:(java,java)