可能造成內(nèi)存溢出的原因:
- 一次性把txt文件讀取到內(nèi)存
- 頻繁的new對(duì)象
實(shí)體類(lèi)文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-850883.html
import lombok.Data;
import java.io.Serializable;
/**
* @author cpf
* @date 2024/4/13 14:40
*/
@Data
public class User implements Serializable{
private String user;
private String positioningTime;
private String latitude;
private String longitude;
private String locationId;
public void clear() {
setUser(null);
setPositioningTime(null);
setLatitude(null);
setLongitude(null);
setLocationId(null);
}
}
可以使用對(duì)象池解決頻繁new對(duì)象的問(wèn)題
解決一次性把文件讀取到內(nèi)存: 可以使用文件流方式,使用java.util.Scanner類(lèi)掃描文件的內(nèi)容,一行一行連續(xù)地讀取文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-850883.html
import org.example.entity.User;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
/**
* @author cpf
* @date 2024/4/13 15:45
*/
public class TestMe {
private static final int USER_POOL_SIZE = 100; // 根據(jù)實(shí)際情況調(diào)整對(duì)象池大小
private static Queue<User> userPool = new LinkedList<>();
static {
// 預(yù)先創(chuàng)建對(duì)象池中的User實(shí)例
for (int i = 0; i < USER_POOL_SIZE; i++) {
userPool.offer(new User());
}
}
public static void main(String[] args) {
String filePath = "src/main/resources/Gowalla_totalCheckins.txt";
List<User> users = readData(filePath);
for (int i = 0; i < 20; i++) {
// 獲取一個(gè)1-6000000的隨機(jī)數(shù)
int random = (int) (Math.random() * 6000000);
System.out.println("第"+ random +"個(gè)數(shù)據(jù): " + users.get(random));
}
System.out.println(users.size());
}
private static List<User> readData(String filePath) {
List<User> userList = new ArrayList<>();
FileInputStream fis = null;
Scanner sc = null;
try {
fis = new FileInputStream(filePath);
sc = new Scanner(fis, "UTF-8");
while (sc.hasNextLine()) {
String line = sc.nextLine();
User user = parseLine(line);
if (user != null) {
userList.add(user);
}
// 在主程序中,使用完User對(duì)象后應(yīng)將其歸還到對(duì)象池
userPool.offer(user);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} finally {
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (sc != null) {
sc.close();
}
}
return userList;
}
private static User parseLine(String line) {
String[] data = line.split("\t");
if (data.length < 5) {
System.err.println("數(shù)據(jù)格式錯(cuò)誤:需要至少包含5個(gè)字段。");
return null;
}
// 從對(duì)象池中獲取一個(gè)User實(shí)例
User user = userPool.poll();
if (user == null) {
// 對(duì)象池為空時(shí),創(chuàng)建新的User實(shí)例
user = new User();
}
// 清除原有數(shù)據(jù)并填充新行數(shù)據(jù)
user.clear();
user.setUser(data[0]);
user.setPositioningTime(data[1]);
user.setLatitude(data[2]);
user.setLongitude(data[3]);
user.setLocationId(data[4]);
return user;
}
}
到了這里,關(guān)于Java讀取600萬(wàn)行的txt文件,內(nèi)存溢出解決方案的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!