java文件操作方法大全

导读:本篇文章讲解 java文件操作方法大全,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

文章目录

方法

	mkdir,//创建目录
	strWriteFile,//字符串写入文件
	deleteFolder,//删除文件夹
	copyDirectiory,//拷贝目录
	copyFile,//拷贝文件
	getDocumentList,//获取文件夹列表或文件列表
	readTxtToStr,//读取txt文件

具体实现

public class FileHelper {

	private static final Logger logger = LoggerFactory.getLogger(FileHelper.class);
	

	/**
	 * 创建目录
	 * 
	 * @author qitianersheng
	 */
	public static String mkdir(String dirPath) {
		File file = new File(dirPath);
		if (!file.exists() && !file.mkdirs()) {
			logger.error("创建文件夹失败,请查看相关权限");
			return "fail";
		}
		return "success";
	}

	/**
	 * 字符串写入文件
	 * 
	 * @author qitianersheng
	 */
	public static void strWriteFile(String str, String path, String fileName) {
		File folder = new File(path);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		path = path + fileName;
		logger.info("File storage path:{}", path);
		File txt = new File(path);
		try (FileOutputStream fos = new FileOutputStream(txt)) {
			if (!txt.exists()) {
				txt.createNewFile();
			}
			byte bytes[] = new byte[512];
			bytes = str.getBytes();
			int b = bytes.length;
			fos.write(bytes, 0, b);
		} catch (FileNotFoundException e) {
			logger.error("FileNotFound:", e);
		} catch (IOException e) {
			logger.error("IOException:", e);
		}
	}

	/**
	 * 删除文件夹
	 * @author qitianersheng
	 */
	public static void deleteFolder(File file) {
		if (!file.exists()) {
			return;
		}
		if (file.isFile()) {
			file.delete();
		} else if (file.isDirectory()) {
			for (File f : file.listFiles()) {
				deleteFolder(f);
			}
			file.delete();
		}
	}

	/**
	 * 拷贝文件夹
	 * 
	 * @author qitianersheng
	 */
	public static void copyDirectiory(String sourceDir, String targetDir) throws IOException {
		// 新建目标目录
		(new File(targetDir)).mkdirs();
		// 获取源文件夹当前下的文件或目录
		File[] file = (new File(sourceDir)).listFiles();
		for (int i = 0; i < file.length; i++) {
			if (file[i].isFile()) {
				// 源文件
				File sourceFile = file[i];
				// 目标文件
				File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());
				copyFile(sourceFile, targetFile);
			}
			if (file[i].isDirectory()) {
				// 准备复制的源文件夹
				String dir1 = sourceDir + "/" + file[i].getName();
				// 准备复制的目标文件夹
				String dir2 = targetDir + "/" + file[i].getName();
				copyDirectiory(dir1, dir2);
			}
		}
	}

	/**
	 * 拷贝文件
	 * 
	 * @author qitianersheng
	 */
	private static void copyFile(File sourceFile, File targetFile) {
		// 新建文件输入流并对它进行缓冲
		try (FileInputStream input = new FileInputStream(sourceFile);
				BufferedInputStream inBuff = new BufferedInputStream(input);
				// 新建文件输出流并对它进行缓冲
				FileOutputStream output = new FileOutputStream(targetFile);
				BufferedOutputStream outBuff = new BufferedOutputStream(output)) {
			// 缓冲数组
			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			// 刷新此缓冲的输出流
			outBuff.flush();
		} catch (IOException e) {
			logger.error("copyFile()  error:", e);
		}
	}

	/**
	 * 获取文件夹列表或文件列表
	 * 
	 * @return List<String>
	 * @author qitianersheng
	 */
	public static List<String> getDocumentList(String path, Boolean isFolder) {
		List<String> list = new ArrayList<>();
		File baseFile = new File(path);
		if (baseFile.isFile() || !baseFile.exists()) {
			return list;
		}
		File[] files = baseFile.listFiles();
		if (isFolder) {
			for (File file : files) {
				if (file.isDirectory()) {
					list.add(file.getName());
				}
			}
		} else {
			for (File file : files) {
				if (file.isFile()) {
					list.add(file.getName());
				}
			}
		}
		return list;
	}

	/**
	 * 读取txt文件
	 * @author qitianersheng
	 */
	public static String readTxtToStr(String path) {
		StringBuffer buffer = new StringBuffer();
		try (BufferedReader bf = new BufferedReader(new FileReader(path))) {
			String s = null;
			while ((s = bf.readLine()) != null) {// 使用readLine方法,一次读一行
				buffer.append(s.trim());
			}
		} catch (Exception e) {

		}
		return buffer.toString();

	}
	
}

  • 文章是个人知识点整理总结,如有错误和不足之处欢迎指正。
  • 如有疑问、或希望与笔者探讨技术问题(包括但不限于本章内容),欢迎添加笔者微信(o815441)。请备注“探讨技术问题”。欢迎交流、一起进步。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/69842.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!