JAVA怎么把TXT文件读取出来封装到数组里 返回String

如题所述

您是指,整个文件读取为一个字符串,还是一行一条字符串的字符串数数组?


import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

/**
 * 2016年9月2日下午5:42:55
 *
 * @author 3306 TODO Have fun
 */
public class FileUtil {

    public static void main(String[] args) {

        String path = "D://Hello.java";//这里请修改为您的文件
        try {
            for (String each : readFile(path)) {
                System.out.println(each);
            }


            System.out.println("\n\n----------------------------------\n\n");


            System.out.println(readFileForOneLine(path));//文件内容全部为一个字符串

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 读取文件内容
     *
     * @param path 文件详细路径
     *             如: D://my.txt
     * @return List<String>
     * @throws IOException java.IO异常
     */
    public static List<String> readFile(String path) throws IOException {

        File targetFile = new File(path);
        List<String> fileContent = new ArrayList<>();//存放文件内容

        if (targetFile.exists()) {

            RandomAccessFile randomAccessFile = new RandomAccessFile(targetFile, "r");//赋予文件读取权限
            String eachLine;
            while (null != (eachLine = randomAccessFile.readLine())) {
                fileContent.add(eachLine);
            }
        }

        return fileContent;

    }


    /**
     * 读取文件内容
     *
     * @param path 文件详细路径
     *             如: D://my.txt
     * @return String
     * @throws IOException java.IO异常
     */
    public static String readFileForOneLine(String path) throws IOException {

        File targetFile = new File(path);
        StringBuilder fileContent = new StringBuilder();

        if (targetFile.exists()) {

            RandomAccessFile randomAccessFile = new RandomAccessFile(targetFile, "r");//赋予文件读取权限
            String eachLine;
            while (null != (eachLine = randomAccessFile.readLine())) {
                fileContent.append(eachLine + "\n");
            }
        }

        return fileContent.toString();

    }

}

追问

一行一个字符串

追答

第一个方法就是了

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-09-20
fdgvfdvbhghdgh追问

有病?

相似回答