Java 创建文件夹和文件,字符串写入文件,读取文件

时间:2023-03-10 04:29:29
Java 创建文件夹和文件,字符串写入文件,读取文件

两个函数如下:

TextToFile(..)函数:将字符串写入给定文本文件;
createDir(..)函数:创建一个文件夹,有判别是否存在的功能。
  public void TextToFile(final String strFilename, final String strBuffer)
{
try
{
// 创建文件对象
File fileText = new File(strFilename);
// 向文件写入对象写入信息
FileWriter fileWriter = new FileWriter(fileText); // 写文件
fileWriter.write(strBuffer);
// 关闭
fileWriter.close();
}
catch (IOException e)
{
//
e.printStackTrace();
}
}
public static boolean createDir(String destDirName) {
File dir = new File(destDirName);
if (dir.exists()) {
System.out.println("创建目录" + destDirName + "失败,目标目录已经存在");
return false;
}
if (!destDirName.endsWith(File.separator)) {
destDirName = destDirName + File.separator;
}
//创建目录
if (dir.mkdirs()) {
System.out.println("创建目录" + destDirName + "成功!");
return true;
} else {
System.out.println("创建目录" + destDirName + "失败!");
return false;
}
}
 /**
* 功能:Java读取txt文件的内容
* 步骤:1:先获得文件句柄
* 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
* 3:读取到输入流后,需要读取生成字节流
* 4:一行一行的输出。readline()。
* 备注:需要考虑的是异常情况
* @param filePath
*/
public static void readTxtFile(String filePath){
try {
String encoding="utf-8";
File file=new File(filePath);
if(file.isFile() && file.exists()){ //判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file),encoding);//考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
System.out.println(lineTxt);
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
} }