Java第一次读文件慢_Java 关于文件读取速度问题,求助,谢谢啦

展开全部

/**

* ip条目实体类

*/

public class IpEntry {

String country, province, city, region, local;

long start = 0, end = 0;

public String getCountry() {

return country;

}

public String getProvince() {

return province;

}

public String getCity() {

return city;

}

public String getRegion() {

return region;

}

public String getLocal() {

return local;

}

/**

* 接受字符串初始化属性62616964757a686964616fe59b9ee7ad9431333337376331

* @param text

*/

public IpEntry(String text) {

String fields[] = text.split(",");

start = Long.parseLong(fields[1]);

end = Long.parseLong(fields[3]);

country = fields[5];

province = fields[6];

city = fields[7];

region = fields[8];

local = fields[9];

}

}

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;

/**

* ip地址表类

*/

public class IpTable {

List table;

//读取文件写入, 逐行构造IpEntry, 写入list

public IpTable(String fileName) {

BufferedReader rd = null;

String line;

table = new LinkedList();

try {

rd = new BufferedReader(new FileReader(fileName));

while (true) {

line = rd.readLine();

if (null == line)

break;

table.add(new IpEntry(line));

}

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

//IO资源必须在finally中关闭

rd.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

//匹配第一条

public IpEntry matchFirst(long ip) {

for (IpEntry entry : table) {

if (entry.start <= ip && entry.end >= ip)

return entry;

}

return null;

}

//匹配所有

public IpEntry[] matchAll(long ip) {

List list = new ArrayList();

for (IpEntry entry : table) {

if (entry.start <= ip && entry.end >= ip)

list.add(entry);

}

return list.toArray(new IpEntry[list.size()]);

}

//静态方法

static final String IP_TABLE_FILE_NAME = "E://12.txt";

static IpTable instance = null;

public static IpEntry match(long ip) {

//仅在第一次调用时,初始化静态实例读取文件

if (instance == null)

instance = new IpTable(IP_TABLE_FILE_NAME);

return instance.matchFirst(ip);

}

//你要的方法

public static String getIpCountry(String ip) {

return match(ipToLong(ip)).getCountry();    //你自己的ipToLong方法

}

//模拟测试

public static void main(String[] args) {

String ip[] = {

"192.168.1.1",

//...

"220.10.10.135"

};

for (int i = 0; i 

System.out.println(IpTable.getIpCountry(ip[i]));

}

}

}

可能你一下转不过来,根据你代码里给的结构给你写了个完整的示例。

主要就是把文件内容读取后格式化放在内存对象中,让后只要在对象中查找匹配,就不用再去读取文件了。关于性能优化的话,因为每次都是顺序迭代查找,所以用了LinkedList,其他的话暂时也想不出什么可以优化的地方了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值