IO操作

标准字符集常量定义类:
StandardCharsets.UTF_8

获取文件路径:

System.out.println(System.getProperty("user.dir"));
/*结果:D:\IdeaProjectsMe\project-task*/
image.png
Application.class.getClassLoader().getResourceAsStream("rpc.properties")
或
Thread.currentThread().getContextClassLoader().getResourceAsStream("application.yml");、
/*结果:D:\IdeaProjectsMe\argus-task*/
image.png
//获取绝对路径
System.out.println(Application.class.getProtectionDomain().getCodeSource().getLocation().getFile());
image.png

Read

读取yml文件:

     InputStream is = null;
     try {
         is = Thread.currentThread().getContextClassLoader().getResourceAsStream("application.yml");
         Yaml yaml = new Yaml();
         String result = yaml.dumpAsMap(yaml.load(is));
         //...
     }

result内容如下:


image.png

Java循环读取txt文本中的一行(findBug可能出现Reliance on default encoding风险)

try {
    File file = new File("D:\\PythonWorkspace\\ReportData\\" + ramp_alarm_filename);
    BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

    String line;
    while ((line = bufferedReader.readLine()) != null) {
        String[] lines = line.split("\t");

    }
} catch (Exception e) {
    
}

读取JSON文件

package com.idss.liaoning.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;

/**
 * 读取json文件
 */
public class ReadJsonUtil {

    private static final Logger LOGGER = LogManager.getLogger(ReadJsonUtil.class.getName());

    /**
     * 读取 JSONObject
     *
     * @param fileName 文件名
     * @return JSONObject
     */
    public static JSONObject readJsonObject(String fileName) {
        try {
            File file = new File(System.getProperty("user.dir") + "/json/liaoning/manage/" + fileName);
            String content = FileUtils.readFileToString(file, "UTF-8");
            return JSONObject.parseObject(content);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
            return new JSONObject();
        }
    }

    /**
     * 读取 JSONArray
     *
     * @param fileName 文件名
     * @return JSONArray
     */
    public static JSONArray readJsonArray(String fileName) {
        try {
            File file = new File(System.getProperty("user.dir") + "/json/liaoning/manage/" + fileName);
            String content = FileUtils.readFileToString(file, "UTF-8");
            return JSONArray.parseArray(content);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
            return new JSONArray();
        }
    }
}

读取properties文件

properties文件:

loginUrl=http://127.0.0.1
loginName=root
loginPwd=123456
verifyCode=aaaa

读取properties

package com.idss.liaoning.utils;

import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 常量类
 */
public class Constant {

    public static final ConcurrentHashMap propertiesMap;
    public static final String loginUrl;
    public static final String loginName;
    public static final String loginPwd;
    public static final String verifyCode;

    static {
        try {
            InputStream inStream = Constant.class.getClassLoader().getResourceAsStream("element.properties");
            Properties prop = new Properties();
            //此处避免使用prop.load(FileInputStream)从而导致的读取中文乱码问题;      
            //尽量使用prop.load(FileReader)或指定字符集的Stream
            InputStreamReader inputStreamReader = new InputStreamReader(inStream, StandardCharsets.UTF_8);
            prop.load(inputStreamReader);
            propertiesMap = new ConcurrentHashMap((Map)prop);

            loginUrl = propertiesMap.get("loginUrl");
            loginName = propertiesMap.get("loginName");
            loginPwd = propertiesMap.get("loginPwd");
            verifyCode = propertiesMap.get("verifyCode");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}

Write

写文件换行

new FileOutputStream(file, true) 第二个参数为追加

    /**
     * 写文件
     */
    public static boolean modifyEmailProperties() {
        OutputStreamWriter outputStreamWriter = null;
        BufferedWriter bufferedWriter = null;
        try {
            File file = new File("D:\\test//test.txt");
            outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file, true), StandardCharsets.UTF_8);
            bufferedWriter = new BufferedWriter(outputStreamWriter);
            
            bufferedWriter.newLine();
            bufferedWriter.write("==========");
            bufferedWriter.flush();
            return true;
        } catch (IOException e) {
            logger.error("文件找不到.......", e);
            return false;
        } finally {
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    logger.error("修改配置信息文件 bufferedWriter.close 异常.......", e);
                }
            }
            if (outputStreamWriter != null) {
                try {
                    outputStreamWriter.close();
                } catch (IOException e) {
                    logger.error("修改配置信息文件 outputStreamWriter.close 异常.......", e);
                }
            }
        }
    }

java修改文件的多行内容

思路:
1、将文件内容一行一行的读出来
2、在每读一行的时候,判断是否以a或b开始,如果是则进行处理,然后写到缓冲对象。如果不是则直接写入缓冲对象中
3、将缓冲对象中的内容回写到文件中

完整代码如下:

import java.io.BufferedReader;  
import java.io.BufferedWriter;  
import java.io.FileReader;  
import java.io.FileWriter;  
import java.io.IOException;  
  
/** 
 * 修改文件 
 */  
public class FileModify {  
  
    /** 
     * 读取文件内容 
     *  
     * @param filePath 
     * @return 
     */  
    public String read(String filePath) {  
        BufferedReader br = null;  
        String line = null;  
        StringBuffer buf = new StringBuffer();  
          
        try {  
            // 根据文件路径创建缓冲输入流  
            br = new BufferedReader(new FileReader(filePath));  
              
            // 循环读取文件的每一行, 对需要修改的行进行修改, 放入缓冲对象中  
            while ((line = br.readLine()) != null) {  
                // 此处根据实际需要修改某些行的内容  
                if (line.startsWith("a")) {  
                    buf.append(line).append(" start with a");  
                }  
                else if (line.startsWith("b")) {  
                    buf.append(line).append(" start with b");  
                }  
                // 如果不用修改, 则按原来的内容回写  
                else {  
                    buf.append(line);  
                }  
                buf.append(System.getProperty("line.separator"));  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            // 关闭流  
            if (br != null) {  
                try {  
                    br.close();  
                } catch (IOException e) {  
                    br = null;  
                }  
            }  
        }  
          
        return buf.toString();  
    }  
      
    /** 
     * 将内容回写到文件中 
     *  
     * @param filePath 
     * @param content 
     */  
    public void write(String filePath, String content) {  
        BufferedWriter bw = null;  
          
        try {  
            // 根据文件路径创建缓冲输出流  
            bw = new BufferedWriter(new FileWriter(filePath));  
            // 将内容写入文件中  
            bw.write(content);  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            // 关闭流  
            if (bw != null) {  
                try {  
                    bw.close();  
                } catch (IOException e) {  
                    bw = null;  
                }  
            }  
        }  
    }  
      
    /** 
     * 主方法 
     */  
    public static void main(String[] args) {  
        String filePath = "C:/file.txt"; // 文件路径  
        FileModify obj = new FileModify();  
        obj.write(filePath, obj.read(filePath)); // 读取修改文件  
    }  
  
}  

你可能感兴趣的:(IO操作)