JavaIO读取文件内容

本示例的应用场景:

读取模板文件夹的模板文件,然后替换占位符,生成指定文件到指定文件夹。

由于不同用户有不同的地址,所以需要在配置文件中编辑属于自己的两个地址

    项目地址:ProjectPath

    模板地址:FtlPath

    配置文件地址:filePath

配置文件放在项目WorkSpace下,导出jar后可以放置在jar包同级目录

示例内容如下:

#项目地址
ProjectPath=D:/WorkSpace/project
#模板地址
FtlPath=D:/WorkSpace

代码如下:

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.File;

public class testIO {
    public static void main(String[] args) {
        String ProjectPath = null;
        String FtlPath = null;
        String filePath = System.getProperty("user.dir")
                + "\\filePath.txt";
        try {
            String encoding = "GBK";
            File file = new File(filePath);
            System.out.println("filePath"+filePath);
            if (file.isFile() && file.exists()) { // 判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file), encoding);// 考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    if ("#".equals(lineTxt.substring(0, 1))) {

                    } else {
                        if ("P".equals(lineTxt.substring(0, 1))) {
                            ProjectPath = lineTxt.substring(12,
                                    lineTxt.length());
                            System.out.println("ProjectPath:"+ProjectPath);
                        } else if ("F".equals(lineTxt.substring(0, 1))) {
                            FtlPath = System.getProperty("user.dir") + "/ftl/";
                            System.out.println("FtlPath"+FtlPath);
                        }
                    }
                }
                read.close();
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
    }
}

String filePath = System.getProperty("user.dir") + "\\filePath.txt";

System.getProperty("user.dir")  获取程序的位置,加上文件名filePath.txt 即为配置文件地址

while循环中,每次读取一行,若是#开头的则不做任何处理,直接读取下一行

接下来判断开头是ProjectPath还是FtlPath,分别存到各自变量中

当中存在编码问题也用InputStreamReader时设置了编码,所以不会出现中文乱码问题

 

 

转载于:https://my.oschina.net/xiaozhiwen/blog/1586968

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值