其他分享
首页 > 其他分享> > 读取文件转存到数组的工具类

读取文件转存到数组的工具类

作者:互联网

cu1909,rb1909

转成
cu1909
rb1909

package ctpdemo;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import static com.sun.org.apache.bcel.internal.classfile.Utility.printArray;

public class FileUtis {
    public static void main(String[] args)  throws Exception{
        // 指定的文件
        File file = new File("D:\\Program Files (x86)\\Desktop\\ctpdemo\\resources\\test.properties");
        String str = fileTest(file);
        String[] strArray=null;

        strArray = convertStrToArray(str);
        String s = printArray(strArray);
        for (String s1 : strArray) {
            System.out.println(s1);
        }
    }
    //使用String的split 方法
    public static String[] convertStrToArray(String str){
        String[] strArray = null;
        strArray = str.split(","); //拆分字符为"," ,然后把结果交给数组strArray
        return strArray;
    }
    private static  String fileTest(File file) throws Exception {
        // 装载list
        List<String> strArray = new ArrayList<String>();
        // 读取文件
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));
        StringBuffer buffer = new StringBuffer();
        String line;

        int i = 0;
        while ((line = br.readLine()) != null) {
            if (i == 0) {
                buffer.append(line + "\n");
            } else {
                // 判断截取点
                if (line.substring(0, 1).equals(",")) {
                    strArray.add(buffer.toString());
                    buffer = new StringBuffer();
                    buffer.append(line + "\n");
                } else {
                    buffer.append(line + "\n");
                }
            }
            i++;
        }
        if (line == null) {
            strArray.add(buffer.toString());
        }
        return buffer.toString();
    }

}

标签:读取,buffer,strArray,数组,new,line,null,转存,String
来源: https://blog.csdn.net/qq_39505065/article/details/97402822