Java输入输出流读出文件、写入文件

1.读取文件

/**
 * 读取文件
 *
 * @param fileName 文件名称,例如 D:/file/test.json
 * @return
 */
public static String readJsonFile(String fileName) {
    
    
    String jsonStr = "";
    try {
    
    
        File jsonFile = new File(fileName);
        FileReader fileReader = new FileReader(jsonFile);
        Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
        int ch = 0;
        StringBuffer sb = new StringBuffer();
        while ((ch = reader.read()) != -1) {
    
    
            sb.append((char) ch);
        }
        fileReader.close();
        reader.close();
        jsonStr = sb.toString();
        return jsonStr;
    } catch (IOException e) {
    
    
        e.printStackTrace();
        return null;
    }
}

2.一行一行读取文件

public static List<String> getLineInfo(String file) {
    
    
    List<String> strList = new ArrayList<>();
    try {
    
    
        BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(file.getBytes(Charset.forName("utf8"))), Charset.forName("utf8")));
        String line;
        while ((line = br.readLine()) != null) {
    
    
            if (!line.trim().equals("")) {
    
    
                strList.add(line);
            }
        }
    } catch (IOException e) {
    
    
        e.printStackTrace();
    }
    return strList;
}

3.将数据写到文件中(两种都行)

/**
 * 将数据写入到文件中
 *
 * @param content
 * @param filePath
 */
public static void saveAsFileWriter(String content, String filePath) {
    
    
    FileWriter fwriter = null;
    try {
    
    
        // true表示不覆盖原来的内容,而是加到文件的后面。若要覆盖原来的内容,直接省略这个参数就好
        fwriter = new FileWriter(filePath, true);
        fwriter.write(content);
    } catch (IOException ex) {
    
    
        ex.printStackTrace();
    } finally {
    
    
        try {
    
    
            fwriter.flush();
            fwriter.close();
        } catch (IOException ex) {
    
    
            ex.printStackTrace();
        }
    }
}

/**
 * 将内容写入文件中
 * @param filePath
 * @param data
 */
public static void saveDataToFile(String filePath, String data) {
    
    
    BufferedWriter writer = null;
    File file = new File(filePath);
    //如果文件不存在,则新建一个
    if (!file.exists()) {
    
    
        try {
    
    
            file.createNewFile();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
    //写入
    try {
    
    
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF-8"));
        writer.write(data);
    } catch (IOException e) {
    
    
        e.printStackTrace();
    } finally {
    
    
        try {
    
    
            if (writer != null) {
    
    
                writer.close();
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
    System.out.println("文件写入成功!");
}

猜你喜欢

转载自blog.csdn.net/weixin_43484014/article/details/120862730