网站首页  汉语字词  英语词汇  考试资料  写作素材  旧版资料

请输入您要查询的考试资料:

 

标题 Java文件操作类FileManager
内容
    读写文件是最常用的操作之一,每次将相应的代码片段复制过来不仅麻烦,还会影响整体的美观。为此我单独写了一个文件操作的类,需要时先把这个类的代码粘过去,再调用就方便多了。
    import java.io.BufferedReader;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.util.ArrayList;
    import java.util.List;
    public class FileManager {
    public static String read(String fileName, String encoding) {
    StringBuffer fileContent = new StringBuffer();
    try {
    FileInputStream fis = new FileInputStream(fileName);
    InputStreamReader isr = new InputStreamReader(fis, encoding);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    while ((line = br.readLine()) != null) {
    fileContent.append(line);
    fileContent.append(System.getProperty("line.separator"));
    }
    br.close();
    isr.close();
    fis.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    return fileContent.toString();
    }
    public static void write(String fileContent, String fileName, String encoding) {
    try {
    FileOutputStream fos = new FileOutputStream(fileName);
    OutputStreamWriter osw = new OutputStreamWriter(fos, encoding);
    osw.write(fileContent);
    osw.flush();
    osw.close();
    fos.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
    调用示例:
    写入 FileManager.write("Hello, World!", "D:\test.txt", "UTF-8");
    读取 System.out.println(FileManager.read("D:\test.txt", "UTF-8"));
随便看

 

在线学习网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。

 

Copyright © 2002-2024 cuapp.net All Rights Reserved
更新时间:2025/5/26 0:00:28