用Java将对象列表写入txt文件的最快方法
我有一个搜索列表的函数,对于列表中的每个项目,我都有另一个列表。这两个列表必须转换为文本文件才能导入到软件中。我遇到的问题是速度慢 我的第一个列表有大约500条记录,而该列表中的每一条记录都有另一个列表,范围从1条记录到无穷大。这大约需要20分钟才能完成当我评论更新(更新2个列表中每个项目的状态)时,时间下降到9分钟 有人能帮我吗用Java将对象列表写入txt文件的最快方法,java,list,file,Java,List,File,我有一个搜索列表的函数,对于列表中的每个项目,我都有另一个列表。这两个列表必须转换为文本文件才能导入到软件中。我遇到的问题是速度慢 我的第一个列表有大约500条记录,而该列表中的每一条记录都有另一个列表,范围从1条记录到无穷大。这大约需要20分钟才能完成当我评论更新(更新2个列表中每个项目的状态)时,时间下降到9分钟 有人能帮我吗 private String getExportacaoApontamento( String idsExportar,
private String getExportacaoApontamento(
String idsExportar,
String dataInicial,
String dataFinal,
String status,
String tipoFiltro,
String filtro,
String turma,
boolean exportarTodos) throws SQLException {
StringBuilder stringBuilder = new StringBuilder();
try (
Connection conMySql = U_Conexao.getConexaoMySQL();
Connection conOracle = U_Conexao.getConexaoOracle()) {
if (conMySql != null) {
List<C_Sequencia> listSequencia;
R_Sequencia r_Sequencia = new R_Sequencia(conMySql, null);
if (status.equals(String.valueOf(C_Status.TODOS))) {
status = C_Status.PENDENTE + ", " + C_Status.EXPORTADO;
}
String orderBy = "S." + C_Sequencia.DATA + ", S." + C_Sequencia.COD_COLETOR + ", S." + C_Sequencia.COD_FISCAL;
if (exportarTodos == false) {
listSequencia = r_Sequencia.listExportarId(idsExportar, dataInicial, dataFinal, orderBy);
} else {
tipoFiltro = verificarFiltroApontamento(tipoFiltro);
if (filtro == null || filtro.isEmpty()) {
listSequencia = r_Sequencia.listExportarData(dataInicial, dataFinal, status, turma, orderBy);
} else {
listSequencia = r_Sequencia.listExportarFiltro(dataInicial, dataFinal, tipoFiltro, filtro, status, turma, orderBy);
}
}
if (!listSequencia.isEmpty()) {
if (!verificarLiberacoes(listSequencia, conMySql, conOracle)) {
return "-1";
}
C_Sequencia seqAntiga = null;
R_Producao r_Producao = new R_Producao(conMySql, conOracle);
for (C_Sequencia sequencia : listSequencia) {
C_Sequencia seqNova = sequencia;
String retornoSequencia = gerarSequencia(seqAntiga, seqNova);
if (!retornoSequencia.isEmpty()) {
stringBuilder.append(retornoSequencia);
}
List<C_Producao> listProducao = r_Producao.getProducaoExportar(sequencia.getChave(), status);
for (C_Producao producao : listProducao) {
DecimalFormat decimal = new DecimalFormat("########.00");
String prod = String.valueOf(decimal.format(Double.parseDouble(producao.getProducao())));
String meta = String.valueOf(decimal.format(Double.parseDouble(producao.getMeta())));
prod = prod.replace(",", "");
meta = meta.replace(",", "");
stringBuilder.append("02;")
.append(String.format("%5d", producao.getCodColetor())).append(";")
.append(U_DataHora.formatarData(producao.getDataHora(), U_DataHora.DDMMYYYY_HHMMSS, U_DataHora.DDMMYYYY)).append(";")
.append(String.format("%10d", producao.getFuncionario().getMatricula())).append(";")
.append(String.format("%9d", sequencia.getCodCc())).append(";")
.append(String.format("%4d", sequencia.getCodOp())).append(";")
.append(String.format("%4d", sequencia.getCodOp())).append(";")
.append(" ;")
.append(String.format("%6d", Long.parseLong(sequencia.getCodFazenda()))).append(";")
.append(String.format("%6d", Long.parseLong(sequencia.getCodTalhao()))).append(";")
.append(String.format("%10s", prod)).append(";")
.append(" 0000000;")
.append(";")
.append(" ;")
.append(String.format("%9s", meta)).append(";")
.append(String.format("%4d", sequencia.getCodSequencia())).append(";")
.append(" ;")
.append(" ;")
.append(" ;")
.append(" ;")
.append(" ;")
.append(" ;")
.append(String.format("%9d", sequencia.getCodOs())).append(";")
.append("\r\n");
if (producao.getStatus().getStatus() != C_Status.EXPORTADO) {
r_Producao.atualizarStatus(producao.getChave(), C_Status.EXPORTADO); // Atualiza status para exportado
}
}
// Atualiza o status de todas as produções da sequencia da posição atual
//r_Producao.atualizaStatusProducoesPorChaveSequencia(sequencia.getChave(), C_Status.EXPORTADO);
seqAntiga = seqNova;
if (sequencia.getStatus().getStatus() != C_Status.EXPORTADO) {
r_Sequencia.atualizarStatus(sequencia.getChave(), C_Status.EXPORTADO); // Atualiza status para exportado
}
}
}
}
} catch (Exception e) {
U_Log.erro(TAG, e.toString());
return e.toString();
}
return stringBuilder.toString();
}
private String gerarSequencia(C_Sequencia seqAntiga, C_Sequencia seqNova) {
StringBuilder sequenciaBuilder = new StringBuilder();
String texto = sequenciaBuilder.append("01;")
.append(String.format("%5d", seqNova.getCodColetor())).append(";")
.append(U_DataHora.formatarData(seqNova.getData(), U_DataHora.DDMMYYYY_HHMMSS, U_DataHora.DDMMYYYY)).append(";")
.append(String.format("%10d", seqNova.getCodFiscal())).append(";")
.append(String.format("%10d", seqNova.getCodFiscal())).append(";")
.append("\r\n").toString();
if (seqAntiga != null) {
if (!seqAntiga.getData().equals(seqNova.getData())
|| !Objects.equals(seqAntiga.getCodColetor(), seqNova.getCodColetor())
|| !Objects.equals(seqAntiga.getCodFiscal(), seqNova.getCodFiscal())) {
return texto;
} else {
return "";
}
} else {
return texto;
}
}
结果:总时间9分钟
现在,我对构建字符串的部分进行了注释
for (C_Sequencia sequencia : listSequencia) {
...
// here build a part of the string in method " gerarSequencia "
// i commented a part inside method " gerarSequencia "
String retornoSequencia = gerarSequencia(seqAntiga, seqNova);
...
for (C_Producao producao : listProducao) {
...
// Here i commented another part of the string
...
}
}
结果:总时间为14分钟-
实际上,仅运行更新行会引发IOException
private File writeRecords(String filenaam, List<String> records) throws IOException
{
File file = new File(filenaam);
try (FileOutputStream fos = new FileOutputStream(file);
PrintWriter writer = new PrintWriter(fos))
{
records.forEach(rec -> writer.println(rec));
writer.flush();
}
return file;
}
{
文件=新文件(filenaam);
try(FileOutputStream fos=新的FileOutputStream(文件);
PrintWriter=新的PrintWriter(fos))
{
records.forEach(rec->writer.println(rec));
writer.flush();
}
返回文件;
}
如果要压缩文件,请执行以下操作:
private void compressFiles(String zipfile, List<File> files) throws IOException
{
try (FileOutputStream fos = new FileOutputStream(zipfile);
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos)))
{
for (File file : files)
{
ZipEntry entry = new ZipEntry(file.getName());
byte[] bytes = Files.readAllBytes(Paths.get(file.getAbsolutePath()));
zos.putNextEntry(entry);
zos.write(bytes, 0, bytes.length);
zos.closeEntry();
}
zos.finish();
zos.flush();
}
}
private void compressFiles(字符串zipfile,列表文件)引发IOException
{
try(FileOutputStream fos=新的FileOutputStream(zipfile);
ZipOutputStream zos=新的zipoutpstream(新的缓冲输出流(fos)))
{
用于(文件:文件)
{
ZipEntry entry=newzipentry(file.getName());
byte[]bytes=Files.readAllBytes(path.get(file.getAbsolutePath());
zos.putNextEntry(条目);
写入(字节,0,字节.长度);
zos.closeEntry();
}
zos.finish();
zos.flush();
}
}
您有两个问题:
1-您实际上不是在写文件,而是返回一些大字符串。我认为在内存中处理这么大的列表不是个好主意
2-你是如何进行更新的?我想问题是你每行都在打db。您应该立即考虑如何执行此操作。此链接可能有助于解决您的性能问题, 这可能不是文件写入问题,但我认为问题在于字符串操作问题。
我解决了我的问题。我改变了逻辑。实际的问题是在数据库中进行了许多选择,这使得它非常缓慢。现在是单一选择。总时间现在是6秒。我的功能出了问题?你能解释一下吗?A)阅读有关java命名约定的内容“\ux”在类名中没有位置。B) 这个网站主要是英文的。因此,发布大量非英语源代码大大降低了你获得好答案的机会。你糟糕的方法是做太多的事情。你应该把每个“功能”放在自己的方法(或类)中,它们之间有清晰、合理的接口。换句话说:你在这里展示输入的方式让我觉得“我不想花时间阅读它”。其他人显然不介意,但是:更多的人想要阅读你的代码,对你来说就更好。如果你注释掉字符串构建代码,需要多长时间?@Shamit Verma,13分钟。你能创建一个可复制的测试用例吗?(即,删除/屏蔽敏感数据后,可能会发布数据+代码)我使用查询结果进行了更新。在检索到巨大的文本后,我开始写作。在每个回合,我需要更新每个项目的状态。。。因为我以后不能更新,我做了一些测试,但时间是一样的
private void compressFiles(String zipfile, List<File> files) throws IOException
{
try (FileOutputStream fos = new FileOutputStream(zipfile);
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos)))
{
for (File file : files)
{
ZipEntry entry = new ZipEntry(file.getName());
byte[] bytes = Files.readAllBytes(Paths.get(file.getAbsolutePath()));
zos.putNextEntry(entry);
zos.write(bytes, 0, bytes.length);
zos.closeEntry();
}
zos.finish();
zos.flush();
}
}