繁体   English   中英

在Java中从.txt文件读取和保存行问题

[英]Issue reading and saving lines from .txt file in Java

目的与问题

我要完成的任务的目标是从提供的路径中找到并读取文本文件,然后将文本文件的每一行复制到ArrayList<String> 通过调用采用路径的构造函数,可以在某个控件类中创建“ ApplicationFileReader”对象(向其发送String ,“ TextFile.txt” [ src文件夹中FILLED文本文件的名称])。

但是,每当程序运行时,读取路径文件后ArrayList<String>仍然为空。 该代码不会引发IOException ,这可能意味着它能够找到文件,而实际上可能无法将文本行提取到列表中。 (代码运行正常,只是没有输出)。 有什么原因吗? 我应该放弃在其他简单的像这种方法这一个 (虽然我还是很好奇的问题)。

提前致谢

代码说明

ApplicationFileReader对象包含3个实例:2个用于文件路径的Strings和该文件的所有文本,以及一个ArrayList<String>用于包含文本文件的每一行。 默认构造函数将所有内容设置为空。 参数构造函数(采用一个String )通过验证路径和提取文本行来完成对所有3个实例的设置。

我有什么想念的吗? 请评论。

代码: ApplicationFileReader

//TODO: Send exception to LOGGER to print to console

package model;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;

public class ApplicationFileReader {

    public String filePathLocation;
    public String fileText;
    public ArrayList<String> fileTextLines;

    public ApplicationFileReader(){
        filePathLocation = "";
        fileText = "";
        fileTextLines = new ArrayList<String>();
    }

    public ApplicationFileReader(String filePathLocation){
        this.filePathLocation = filePathLocation;
        this.fileText = "";
        fileTextLines = new ArrayList<String>();
        extractFileText(filePathLocation);

        /* Testing */
        for(String s : fileTextLines)
            System.out.println(s);
    }

    public boolean extractFileText(String filePathLocation) {
        if(!validateFilePathLocation(filePathLocation))
            return false;
        try {
            Path path_filePath = Paths.get(filePathLocation);
            fileTextLines.addAll(Files.readAllLines(path_filePath, StandardCharsets.UTF_8));
            for(String eachListLine : fileTextLines){
                fileText += eachListLine;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    private boolean validateFilePathLocation(String filePathLocation) {
        try {
            File temporaryFile = new File(filePathLocation);
            if(!temporaryFile.exists() && temporaryFile.isDirectory())
                throw new IOException();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}

您根本没有在extractTextFile()方法中读取文件。

Files.write()用于将Arraylist的内容写入文件。

您可能要使用Files.readAllLines(path);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM