You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复旧版IP解析Java代码?解决readLine()弃用警告

修复IP解析Java程序中的DataInputStream.readLine()弃用问题

嘿,我懂你现在的处境——十年没碰代码,手腕还受伤没法长时间调试,得快速把这个旧IP解析程序给修好对吧?咱们直接针对那个弃用警告来改,一步到位。

问题根源

DataInputStream.readLine()被弃用的核心原因是它处理字符编码的逻辑有缺陷,没法正确处理非ASCII字符,而且Java早就提供了更靠谱的文本读取方案:BufferedReader。

改写后的完整代码

我把原来的代码做了最小改动,保留所有原有功能,同时解决弃用问题:

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ips {
    private static Pattern ex = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
    private static Matcher match;
    static Writer output;
    static int loop = 0;

    public static void main(String[] args) throws IOException{
        String filen = args[0];
        File file = new File(filen);
        // 替换DataInputStream为BufferedReader,指定UTF-8编码避免乱码
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
        output = new BufferedWriter(new FileWriter("ips"));
        
        String it;
        // 用BufferedReader的readLine()循环,读到末尾返回null时结束
        while ((it = br.readLine()) != null) {
            match = ex.matcher(it);
            while (match.find() ){
                System.out.println( match.group() );
                output.write(match.group()+"\n");
                loop++;
            }
        }
        // 别忘了关闭BufferedReader,保证资源释放
        br.close();
        output.close();
        System.out.println("Done parsing the Nmap log.\n"+loop+" ips total.");
    }
}

关键改动说明

  • 把DataInputStream替换成BufferedReader,并且通过InputStreamReader指定了UTF-8编码,避免读取文件时出现乱码问题
  • 调整了读取循环的写法:BufferedReader.readLine()在文件末尾会返回null,所以循环条件改成while ((it = br.readLine()) != null),这是Java读取文本文件的标准写法
  • 新增了关闭BufferedReader的代码,确保IO资源被正确释放

这样改完之后,编译时的弃用警告就会消失,程序功能和原来完全一致,而且更符合Java的最新规范。

内容的提问来源于stack exchange,提问作者NewbButTryin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 22:37:29