linqy的个人博客分享 http://blog.sciencenet.cn/u/linqy

博文

java文件的读写与与路径的判断

已有 2029 次阅读 2017-10-23 10:04 |个人分类:java|系统分类:科研笔记| java, 文件读写, 路径的判断

java文件路径的判断

文件的创建和读写

//read TXT file
class HotClickFile{
public void TxtReader(){
String filepath = "D:\\java_test\\lucene\\data\\searchdata\\HotClick1.txt"; // 绝对路径或相对路径都可以,这里是绝对路径,写入文件时演示相对路径
File file = new File(filepath); // 要读取以上路径的HotClick.txt文件
if (!file.exists()) {//判断文件目录的存在
System.out.println("文件不存在!");
System.exit(0);
}
try { // 防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw
           /* 读入TXT文件 */
FileInputStream fileInputStream = null;
fileInputStream = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(fileInputStream); // 建立一个输入流对象reader
BufferedReader br = new BufferedReader(reader); // 建立一个对象
String line = "";
line = br.readLine();
String []lines = null;
Vector<String[]> hotclick = new Vector<String[]>();
while (line != null) {
lines = line.split(";");
hotclick.add(lines);
line = br.readLine(); // 一次读入一行数据
}
/* 写入Txt文件 */
String fpath = "D:\\java_test\\lucene\\data\\searchdata\\output2.txt";
File writein = new File(fpath);
if(!writein.exists())
{
try {
writein.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
BufferedWriter out = new BufferedWriter(new FileWriter(writein));
for(String[] str:hotclick){
out.write(str[0]+" "+str[1]+" "+str[2]+"\n"); // \r\n即为换行
}
out.flush(); // 把缓存区内容压入文件
out.close(); // 最后记得关闭文件
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}

}




https://blog.sciencenet.cn/blog-3134052-1082057.html

上一篇:IDE简单介绍
下一篇:java基于geotools开源包对shp文件的读取
收藏 IP: 111.195.162.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-5-13 02:09

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部