java生成txt文件并且读写

SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String currentTime = formatter.format(System.currentTimeMillis());// 当前时间作为文件名字
System.out.println(currentTime);
//String path = "D:\\";
String path = "\\\\172.16.151.120\\程序共享";
File file = new File(path);
if(!file.exists()){
    file.mkdirs();
}
/*try {
    file.createNewFile();
} catch (IOException e) {
    e.printStackTrace();
}*/
File f = null;
try {
    f = File.createTempFile(currentTime, ".txt",file);
} catch (IOException e) {
    e.printStackTrace();
}

// write
FileWriter fw = null;
try {
    fw = new FileWriter(f, true);
} catch (IOException e) {
    e.printStackTrace();
}
BufferedWriter bw = new BufferedWriter(fw);
try {
    bw.write(string.toString());
} catch (IOException e) {
    e.printStackTrace();
}
try {
    bw.flush();
} catch (IOException e) {
    e.printStackTrace();
}
try {
    bw.close();
} catch (IOException e) {
    e.printStackTrace();
}
try {
    fw.close();
} catch (IOException e) {
    e.printStackTrace();
}

// read
FileReader fr = null;
try {
    fr = new FileReader(file);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
BufferedReader br = new BufferedReader(fr);
String str = null;
try {
    str = br.readLine();
} catch (IOException e) {
    e.printStackTrace();
}
System.out.println(str);
发布了31 篇原创文章 · 获赞 24 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/hengliang_/article/details/80497129