package tools;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List; import org.bson.Document; /**
* @author chenhuan001
*
*/
public class FileUtil {
String newline = "\r\n";//windows /**
* 写入文件,末尾自动添加\r\n
* utf-8 追加
* @param path
* @param str
*/
public static void writeLog(String path, String str)
{
try
{
File file = new File(path);
if(!file.exists())
file.createNewFile();
FileOutputStream out = new FileOutputStream(file); //true表示追加
StringBuffer sb = new StringBuffer();
sb.append(str + "\r\n");
out.write(sb.toString().getBytes("utf-8"));//
out.close();
}
catch(IOException ex)
{
System.out.println(ex.getStackTrace());
}
} /**
* 写入文件,末尾自动添加\r\n
* @param path
* @param str
*/
public static void writeLog(String path, String str, boolean is_append, String encode)
{
try
{
File file = new File(path);
if(!file.exists())
file.createNewFile();
FileOutputStream out = new FileOutputStream(file, is_append); //true表示追加
StringBuffer sb = new StringBuffer();
sb.append(str + "\r\n");
out.write(sb.toString().getBytes(encode));//
out.close();
}
catch(IOException ex)
{
System.out.println(ex.getStackTrace());
}
}
/**
* 整个文件以string放回,添加\r\n换行
* @param path
* @return
*/
public static String readLogByString(String path)
{
StringBuffer sb=new StringBuffer();
String tempstr=null;
try {
File file=new File(path);
if(!file.exists())
throw new FileNotFoundException();
FileInputStream fis=new FileInputStream(file);
BufferedReader br=new BufferedReader(new InputStreamReader(fis, "utf-8"));
while((tempstr=br.readLine())!=null) {
sb.append(tempstr + "\r\n");
}
} catch(IOException ex) {
System.out.println(ex.getStackTrace());
}
return sb.toString();
} /**
* 加入编码
* 整个文件以string放回,添加\r\n换行
* @param path
* @return
*/
public static String readLogByStringAndEncode(String path, String encode)
{
StringBuffer sb=new StringBuffer();
String tempstr=null;
try {
File file=new File(path);
if(!file.exists())
throw new FileNotFoundException();
FileInputStream fis=new FileInputStream(file);
BufferedReader br=new BufferedReader(new InputStreamReader(fis, encode));
while((tempstr=br.readLine())!=null) {
sb.append(tempstr + "\r\n");
}
} catch(IOException ex) {
System.out.println(ex.getStackTrace());
}
return sb.toString();
} /**
* 按行读取文件,以list<String>的形式返回
* @param path
* @return
*/
public static List<String> readLogByList(String path) {
List<String> lines = new ArrayList<String>();
String tempstr = null;
try {
File file = new File(path);
if(!file.exists()) {
throw new FileNotFoundException();
}
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis, "utf-8"));
while((tempstr = br.readLine()) != null) {
lines.add(tempstr.toString());
}
} catch(IOException ex) {
System.out.println(ex.getStackTrace());
}
return lines;
} public static List<Document> readDocsFromFile(String path) {
List<String> str_docs = readLogByList(path);
List<Document> docs = new ArrayList<Document>();
//System.out.println(str_docs.size());
for (int i = 0; i < str_docs.size(); i++) {
String str_doc = str_docs.get(i);
//System.out.println(str_doc);
Document doc = null;
try{
doc = Document.parse(str_doc);
} catch(Exception e) {
LogUtil.error("\nreadDocsFromFile 中异常, 文件:" + path + "\n第" + i + "行,\n" + str_doc);//好吧有一条没写完...
}
if (null != doc) {
docs.add(doc);
}
}
return docs;
} /**
* 创建目录
* @param dir_path
*/
public static void mkDir(String dir_path) {
File myFolderPath = new File(dir_path);
try {
if (!myFolderPath.exists()) {
myFolderPath.mkdir();
}
} catch (Exception e) {
LogUtil.error("新建目录操作出错");
e.printStackTrace();
}
} /**
* 创建文件
* @param file_path
*/
public static void createNewFile(String file_path) {
File myFilePath = new File(file_path);
try {
if (!myFilePath.exists()) {
myFilePath.createNewFile();
}
}
catch (Exception e) {
LogUtil.error("新建文件操作出错");
e.printStackTrace();
}
} /**
* 递归删除文件或者目录
* @param file_path
*/
public static void deleteEveryThing(String file_path) {
try{
File file=new File(file_path);
if(!file.exists()){
return ;
}
if(file.isFile()){
file.delete();
}else{
File[] files = file.listFiles();
for(int i=0;i<files.length;i++){
String root=files[i].getAbsolutePath();//得到子文件或文件夹的绝对路径
deleteEveryThing(root);
}
file.delete();
}
} catch(Exception e) {
LogUtil.error("删除文件失败");
}
} /*
* 得到一个文件夹下所有文件
*/
public static List<String> getAllFileNameInFold(String fold_path) {
List<String> file_paths = new ArrayList<String>(); LinkedList<String> folderList = new LinkedList<String>();
folderList.add(fold_path);
while (folderList.size() > 0) {
File file = new File(folderList.peekLast());
folderList.removeLast();
File[] files = file.listFiles();
ArrayList<File> fileList = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
folderList.add(files[i].getPath());
} else {
fileList.add(files[i]);
}
}
for (File f : fileList) {
file_paths.add(f.getAbsoluteFile().getPath());
}
}
return file_paths;
} public static void main(String[] args) {
// String path = "C:\\Users\\chenhuan001\\workspace\\CrawlSinaBySelenium\\src";
// List<String> file_paths = getAllFileNameInFold(path);
// for(String file_path : file_paths) {
// System.out.println(file_path);
// }
deleteEveryThing("C:\\Users\\chenhuan001\\Desktop\\testDelete.txt");
// TODO Auto-generated method stub
// List<Document> docs = readDocsFromFile("Data/user_program_data.txt");
// System.out.println(docs.size());
// for (int i = 0; i < docs.size(); i++) {
// System.out.println(docs.toString());
// }
//mkDir("tmp_dir");
//createNewFile("tmp_dir/new_file1.txt");
//deleteEveryThing("save.arff");
} }

java FileUtil(文件操作类)的更多相关文章

  1. java csv 文件 操作类

    一个CSV文件操作类,功能比较齐全: package tool; import java.io.BufferedReader; import java.io.BufferedWriter; impor ...

  2. java的文件操作类File

    java.io.File类,是java获取文件/文件夹的所有属性,和完成所有相关操作的类 例子: package test.file.IO; import java.io.*; public clas ...

  3. Java文件操作类效率对比

    前言 众所周知,Java中有多种针对文件的操作类,以面向字节流和字符流可分为两大类,这里以写入为例: 面向字节流的:FileOutputStream 和 BufferedOutputStream 面向 ...

  4. JAVA文件操作类和文件夹的操作代码示例

    JAVA文件操作类和文件夹的操作代码实例,包括读取文本文件内容, 新建目录,多级目录创建,新建文件,有编码方式的文件创建, 删除文件,删除文件夹,删除指定文件夹下所有文件, 复制单个文件,复制整个文件 ...

  5. android 文件操作类简易总结

    android 文件操作类(参考链接) http://www.cnblogs.com/menlsh/archive/2013/04/02/2997084.html package com.androi ...

  6. java中文件操作《一》

    在日常的开发中我们经常会碰到对文件的操作,在java中对文件的操作都在java.io包下,这个包下的类有File.inputStream.outputStream.FileInputStream.Fi ...

  7. C# 文件操作类大全

      C# 文件操作类大全 时间:2015-01-31 16:04:20      阅读:1724      评论:0      收藏:0      [点我收藏+] 标签: 1.创建文件夹 //usin ...

  8. Android FileUtils 文件操作类

    系统路径 Context.getPackageName(); // 用于获取APP的所在包目录 Context.getPackageCodePath(); //来获得当前应用程序对应的apk文件的路径 ...

  9. File 文件操作类 大全

    File  文件操作类  大全 许多人都会对文件操作感到很难  我也是  但是一个好的项目中必定会涉及到文件操作的 文件的复制 粘贴  等等等 公司大佬写了 一个文件操作的工具类 感觉还是棒棒的啦   ...

随机推荐

  1. C语言 · 身份证号码升级

    算法提高 身份证号码升级   时间限制:1.0s   内存限制:256.0MB      问题描述 从1999年10月1日开始,公民身份证号码由15位数字增至18位.(18位身份证号码简介).升级方法 ...

  2. [Linux应用]Linux应用程序输出数据重定向到文件中

    转自:http://blog.chinaunix.net/uid-20680966-id-4698387.html 目的是要让程序的printf的打印能重定向到某个文本中,ctrl+c强制退出后查看文 ...

  3. Log4j 2使用教程<转>

    Log4j 2的好处就不和大家说了,如果你搜了2,说明你对他已经有一定的了解,并且想用它,所以这里直接就上手了. 1. 去官方下载log4j 2,导入jar包,基本上你只需要导入下面两个jar包就可以 ...

  4. .net DLL程序集中打包另一个DLL

    项目中做了一个通用组件的类库,类库中引用了几个第三方组件(DLL),组件发布给同事使用时,需要同时将这几个第三方的DLL一并复制过去,然后添加相关组件的引用. 如何能够将这些第三方的DLL直接打包到我 ...

  5. pip安装的python扩展模块自定义目录

    根据系统不同: Windows是python目录下Lib\site-packages\: Linux是/usr/local/lib/python/dist-packages/.

  6. mysql数据库对时间进行默认的设置

    //----------------------------------------------------------sql语句----------------------------------- ...

  7. Stay hungry, stay foolish. 求知若饥,虚心若愚。

    如果留意我博客的朋友,应该都有看到这句话在我的自我介绍栏目存在了好长一段时间了,另外,我的 QQ.旺旺.MSN等都有这个签名.Stay hungry, stay foolish.(求知若饥,虚心若愚) ...

  8. 第二百八十八节,MySQL数据库-索引、limit分页、执行计划、慢日志查询

    MySQL数据库-索引.limit分页.执行计划.慢日志查询 索引,是数据库中专门用于帮助用户快速查询数据的一种数据结构.类似于字典中的目录,查找字典内容时可以根据目录查找到数据的存放位置,然后直接获 ...

  9. Can't connect to MySQL server on '192.168.7.175' (10060)

    原因: 1.你的ip没有被授权,无法访问. 2.端口没有打开(如:3306端口没有打开). 解决方法: 授权(http://www.cnblogs.com/SZxiaochun/p/6401424.h ...

  10. nodejs基础 -- buffer缓冲区

    JavaScript 语言自身只有字符串数据类型,没有二进制数据类型.但在处理像TCP流或文件流时,必须使用到二进制数据.因此在 Node.js中,定义了一个 Buffer 类,该类用来创建一个专门存 ...