java文件读取

1.按照字节流和字符流读取文件内容

原码:

package com.anran.filereader;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author anran
 * @version 创建时间:2017年9月9日 上午8:12:29 类说明 :
 */
public class ReadFile {

    public static void main(String[] args) throws Exception, Exception {
        String path = "C:\\Users\\Administrator\\Desktop\\常用缩写.txt";
        readByInputStream(path);
        readByReader(path);
    }

    // 通过字节流读取文件(Java 7的TWR自己会对文件流进行关闭)
    public static void readByInputStream(String path)
            throws FileNotFoundException, IOException {
        try (FileInputStream is = new FileInputStream(path)) {
            int n = 4096;
            byte[] buffer = new byte[n];
            while ((is.read(buffer, 0, n)) != -1) {
                System.out.println(new String(buffer, "UTF-8"));
            }
        }
    }

    // 通过字符流读取文件
    // FileReader可以读取单个字符或者是根据指定位置开始的固定长度的字符,没有可以直接获取一行的方法,FileReader继承了InputStreamReader,但并没有实现父类中带字符集参数的构造函数,所以FileReader只能按系统默认的字符集来解码,然后在UTF-8 -> GBK ->UTF-8的过程中编码出现损失,造成结果不能还原最初的字符。
    public static void readByReader(String path) throws FileNotFoundException,
            IOException {
        // 会出现部分中文乱码
        // try(BufferedReader br = new BufferedReader(new FileReader(path))){
        // String str = null;
        // while(null != (str = br.readLine())){
        // System.out.println(new String(str.getBytes("GBK"),"UTF-8"));
        // }
        // }

        // 直接使用InputStreamReader进行编码设置
        try (BufferedReader br = new BufferedReader(new InputStreamReader(
                new FileInputStream(path), "UTF-8"))) {
            String str = null;
            while (null != (str = br.readLine())) {
                System.out.println(str);
            }
        }
    }

}

文件内容:

Ctrl + Shift + O : 引入imports语句/删除多余的imports语句 
Ctrl + Shift + T ; 打开Open Type查找类文件(只在java代码中查找)
Ctrl + Shift + F ; 代码格式化(在中文输入法下快捷键被占用)
Ctrl + Shift + ←(→) : 选中从当前光标位置左右的内容
Shift + ↓(↑)(←)(→) : 选中光标位置的内容

输出:

Ctrl + Shift + O : 引入imports语句/删除多余的imports语句 
Ctrl + Shift + T ; 打开Open Type查找类文件(只在java代码中查找)
Ctrl + Shift + F ; 代码格式化(在中文输入法下快捷键被占用)
Ctrl + Shift + ←(→) : 选中从当前光标位置左右的内容
Shift + ↓(↑)(←)(→) : 选中光标位置的内容
Ctrl + Shift + O : 引入imports语句/删除多余的imports语句 
Ctrl + Shift + T ; 打开Open Type查找类文件(只在java代码中查找)
Ctrl + Shift + F ; 代码格式化(在中文输入法下快捷键被占用)
Ctrl + Shift + ←(→) : 选中从当前光标位置左右的内容
Shift + ↓(↑)(←)(→) : 选中光标位置的内容

2.读取properies文件

原码:

package com.anran.filereader;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * @author anran
 * @version 创建时间:2017年9月5日 下午12:45:24 类说明 :
 */
public class ReadProperiesFile {

    private static String path = "E:\\work\\properties.properties";
    // 只读取一次
    private static Properties properties = null;

    public static String read(String key) {
        String value = null;
        try {
            initProperties();
            value = properties.getProperty(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    //初始化properties
    public static void initProperties() throws IOException {
        if (null == properties) {
            System.out.println("初始化");
            properties = new Properties();
            File file = new File(path);
            FileInputStream fi = new FileInputStream(file);
            InputStreamReader reader = new InputStreamReader(fi, "UTF-8");
            //加载对应文件
            properties.load(reader);
            reader.close();
            fi.close();
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            System.out.println(read("name"));
            System.out.println(read("age"));
            System.out.println(read("ip"));
            System.out.println(read("port"));
            System.out.println(read("cnName"));
        }
    }

}

文件内容:

name=anran
age=12
ip=10.144.245.218
port=8080
cnName=安然

输出:

初始化
anran
12
10.144.245.218
8080
安然
anran
12
10.144.245.218
8080
安然
anran
12
10.144.245.218
8080
安然

3.使用jdk中的dom获取xml文件内容

原码:

package com.anran.filereader;

import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/** 
 */
public class ReadXml {

    private static String path = "E:\\work\\properties.xml";

    public static void readByDocument(String country, String province)
            throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(false);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new FileReader(path)));
        //获取根节点元素
        Element root = doc.getDocumentElement();
        //获取所有的country节点列表
        NodeList nodes = root.getElementsByTagName("country");
        //获取对应国家的节点
        Node countryNode = getNode(nodes, "country", country);
        //获取对应省份的节点
        Node provinceNode = getNode(countryNode.getChildNodes(), "province",
                province);
        //获取对应省份下面的城市节点列表
        List<Node> cityNode = getChildNode(provinceNode.getChildNodes(), "city");
        for (int i = 0; i < cityNode.size(); i++) {
            Node node = cityNode.get(i);
            //node.getFirstChild().getNodeValue()获取节点中的内容
            System.out.println("城市名称:" + getAttribute(node, "name") + " 城市编号:"
                    + node.getFirstChild().getNodeValue());
        }
    }

    // 获取对应节点中属性的值
    private static String getAttribute(Node node, String name) {
        //node.getAttributes()获取节点属性列表
        NamedNodeMap namedNodeMap = node.getAttributes();
        //遍历属性
        for (int j = 0; j < namedNodeMap.getLength(); j++) {
            Node newNode = namedNodeMap.item(j);
            // getNodeName()获取属性名称
            if (name.equals(newNode.getNodeName())) {
                // getNodeValue()获取属性的值
                return newNode.getNodeValue();
            }
        }
        return null;
    }

    // 获取节点列表中对应属性的节点
    private static Node getNode(NodeList nodeList, String nodeName, String key) {
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
             getNodeName()获取节点标签
            if (node.getNodeName().equals(nodeName)) {
                if (key.equals(getAttribute(node, "name"))) {
                    return node;
                }
            }
        }
        return null;
    }

    // 获取对应节点中对应名称的值
    private static List<Node> getChildNode(NodeList nodeList, String nodeName) {
        List<Node> newList = new ArrayList<Node>();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            // getNodeName()获取节点标签
            if (node.getNodeName().equals(nodeName)) {
                newList.add(node);
            }
        }
        return newList;
    }

    public static void main(String[] args) throws Exception {
        readByDocument("china", "shaanxi");
    }
}

文件内容:

<?xml version="1.0" encoding="utf-8"?>
<root>
    <country name='china'>
        <province name='shaanxi'>
            <city name='xian'>110</city>
            <city name='xianyang'>中国1</city>
        </province>
        <province name='sichuan'>
            <city name='chengdu'>210</city>
            <city name='wenchaun'>211</city>
        </province>
    </country>
    <country name='us'>
        <province name='flld'>
            <city name='ccc'>sss</city>
        </province>
        <province name='jz'>
            <city name='xxx'>xxxx</city>
        </province>
    </country>
</root>

输出:

城市名称:xian 城市编号:110
城市名称:xianyang 城市编号:中国1

4.使用dom4j解析xml(dom4j-1.6.1.jar)

原码:

package com.anran.filereader;

import java.io.File;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/** 
 * @author anran
 * @version 创建时间:2017年9月5日 下午6:59:17
 * 类说明 : 
 */
public class ReadXmlByDom4j {

    private static final String path = "E:\\work\\properties.xml";
    @SuppressWarnings({ "unused", "unchecked" })
    public static void read(String country, String province, String city) throws Exception{
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File(path));
        //获取根节点元素
        Element root = document.getRootElement();
        //获取对应节点下面的对应标签列表
        List<Element> countryNodeList = root.elements("country");
        System.out.println(countryNodeList.size());
        for (Element element : countryNodeList){
            //获取对应节点的标签
            System.out.println(element.getName());
            //获取对应节点的属性
            System.out.println(element.attributeValue("name"));
            List<Element> provinceNodeList = element.elements("province");
            for (Element elementProvince : provinceNodeList){
                System.out.println(elementProvince.attributeValue("name"));
                List<Element> cityNodeList = elementProvince.elements("city");
                for (Element elementCity : cityNodeList){
                    //获取属性值
                    System.out.println(elementCity.attributeValue("name"));
                    //获取标签内的值
                    System.out.println(elementCity.getStringValue());
                    //获取标签内的值
                    System.out.println(elementCity.getText());
                }

            }
        }
    }

    public static void main(String[] args) throws Exception {
        read("china", "shaanxi","xian");
    }
}

文件内容:

<?xml version="1.0" encoding="utf-8"?>
<root>
    <country name='china'>
        <province name='shaanxi'>
            <city name='xian'>110</city>
            <city name='xianyang'>中国1</city>
        </province>
        <province name='sichuan'>
            <city name='chengdu'>210</city>
            <city name='wenchaun'>211</city>
        </province>
    </country>
    <country name='us'>
        <province name='flld'>
            <city name='ccc'>sss</city>
        </province>
        <province name='jz'>
            <city name='xxx'>xxxx</city>
        </province>
    </country>
</root>

输出:

2
country
china
shaanxi
xian
110
110
xianyang
中国1
中国1
sichuan
chengdu
210
210
wenchaun
211
211
country
us
flld
ccc
sss
sss
jz
xxx
xxxx
xxxx
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值