java读取txt文件一行不同类型并存入_java实现读取文件内容(不同类型)

在一些项目中大量的数据经常需要从文件中读取,例如xml文件,txt文件,csv文件

1.读取本地的xml文件,需要注意对应的路径

//读取xml文件,xmlFile为读取文件的路径

DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();

DocumentBuilder builder=factory.newDocumentBuilder();

Document document=builder.parse(xmlFile);

NodeList nodeList= document.getElementsByTagName(thisTag);//指定标签(thisTag)的节点集合

for(itn i =0;i

Node node =nodeList.item(i);

NamedNodeMap attributes=node.getAttributes();for (int j = 0; j < attributes.getLength(); j++) {

Node attribute=attributes.item(j);

System.out.println(attribute.getNodeName()+ ":"

+attribute.getNodeValue());

}

}

注意:getElementsByTagName()方法只是属于document 与Element 的方法

所以,当针对某个Node 查找对应的节点时,需要先强制转换为Element

Element nodeToElement =(Element) node;

NodeList osNodeList= nodeToElement.getElementsByTagName(thisTag);//thisTag为指定标签

2.读取txt文件

一般的数据存储都是键值对的方式在文件中记录,开发人员多是根据已知的键,从文件中取得对应的值。

例如Config.txt 中内容为:

name=jack

sex=boy

要从java程序中读取该文件的内容

File config_file = new File("./Config") ; //此处使用相对路径

String config_file_fullpath =config_file.getAbsoluteFile().toString() ;

readConfig config= newreadConfig (config_file_fullpath) ;

String name= config.get("name");//name为jack

//对获取的数据进行处理

//...

3.读取.csv文件

csv文件一般为表格,是多行多列的数据,列对应相应不同的属性,java实现逐行读取每列单元格的值。

需要用到jar包(javacsv.jar)

CsvReader csv_reader = null;char delimiter = ',';try{

csv_reader= new CsvReader(paramInfoFile, delimiter);//paramInfoFile为读取的csv文件路径

csv_reader.setEscapeMode(CsvReader.ESCAPE_MODE_DOUBLED);

csv_reader.readHeaders();

}catch(Exception e) {//TODO Auto-generated catch block

e.printStackTrace();

}try{while(csv_reader.readRecord()) {

String str= csv_reader.get(0);if(str.startsWith("#")){continue;

}

String paramType= csv_reader.get(0);//该行的第一列数据

String class1= csv_reader.get(1);//该行的第二列数据,以此类推

String variable= csv_reader.get(2);}}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值