IO操作

作者: 青丝如梦 | 来源:发表于2019-05-05 15:24 被阅读0次

标准字符集常量定义类:
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<String, String> 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<String, String>((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操作其实可以分成两个步骤,请求IO操作和执行IO操作。一般的IO调用过程是这样的:发起IO操作的请求,执行IO...

  • 文件 io

    文件操作 io读操作 io写操作 复制文件 断点续传 bufio包 func NewReader(rd io.Re...

  • linux IO多路复用笔记

    什么是IO io是数据的接收和发送操作,linux进程无法直接操作io设备,需要通过系统调用请求内核来完成io操作...

  • IO 编程模型(java篇) 精华一页纸

    通常的IO操作,只要不是操作系统内存的数据,基本都是IO操作,常见的IO操作,一般都是 操作磁盘、网卡这些(串口这...

  • 阻塞IO与多路复用

    IO操作 在内存中存在数据交换的操作都可以认为是IO操作 IO密集型程序 在程序执行过程中存在大量IO操作,而cp...

  • IO操作

    1、File的简单操作 2、节点流与功能流2.1、节点流字节流:InputStream、OutputStream、...

  • IO操作

    标准字符集常量定义类:StandardCharsets.UTF_8 获取文件路径: Read 读取yml文件: I...

  • IO操作

    一、什么是IO流I:就是input 、O:就是output ,故称:输入输出流。将数据读入内存或者内存输出的过程常...

  • io操作

    从上到下:1.ios_base类 表示流的一般特征,如是否可读取、是二进制流还是文本流等。2.ios类 基于ios...

  • IO操作

    原文链接http://zhhll.icu/2020/05/18/java%E5%9F%BA%E7%A1%80/IO...

网友评论

      本文标题:IO操作

      本文链接:https://www.haomeiwen.com/subject/fbtbkftx.html