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);

你可能感兴趣的:(java,java生成文件TXT)