package com.dbzhang.io;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class MyFile {
private static String path = "D:/";
private static String filenameTemp;//文件的名字
/**
* 创建文件,false表示没有创建文件,是原先就存在;
*
* @throws IOException
*/
public static boolean creatTxtFile(String name) throws IOException {
boolean flag = false;//判断是否创建文件,false表示没有创建文件
filenameTemp = path + name + ".txt";
File filename = new File(filenameTemp);
if (!filename.exists()) {
filename.createNewFile();
flag = true;
}
return flag;
}
/**
* 写文件
*
* @param newStr
* 新内容
* @throws IOException
*/
public static boolean writeTxtFile(String newStr) throws IOException {
// 先读取原有文件内容,然后进行写入操作
boolean flag = false;
String filein = newStr + "\r\n";
String temp = "";
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
PrintWriter pw = null;
try {
// 文件路径
File file = new File(filenameTemp);
// 将文件读入输入流
fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
// 保存该文件原有的内容
for (int j = 1; (temp = br.readLine()) != null; j++) {
buf = buf.append(temp);
// System.getProperty("line.separator")
// 行与行之间的分隔符 相当于“\n”
buf = buf.append(System.getProperty("line.separator"));
}
buf.append(filein);
fos = new FileOutputStream(file);
pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
flag = true;
} catch (IOException e1) {
// TODO 自动生成 catch 块
throw e1;
} finally {
if (pw != null) {
pw.close();
}
if (fos != null) {
fos.close();
}
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
if (fis != null) {
fis.close();
}
}
return flag;
}
public static void main(String[] args) throws Exception {
boolean isExits = creatTxtFile("zdb1");
String str = "https://blog.csdn.net/youyou_yo/article/details/48164959";
boolean isWrite = writeTxtFile(str);
System.out.println("isExits=="+isExits+"%%%%%isWrite=="+isWrite);
}
}
汇总:
(1)File.exists()方法是用来判断是否存在某个文件,如果存在返回true,否则返回false;
(2)File.createNewFile();方法是用来创建文件
(3)FileInputStream/InputStreamReader/StringBuffer的作用;
(4)BufferedReader.readLine()方法:是判断是否读到流的末尾,如果到达文件末尾,则返回null,