|||
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();
}
}
}
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-9-27 17:24
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社