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. win7控制面板一打开就停止的解决方法

    现象:win7系统,打开控制面板后,弹出提示窗口:资源管理器停止工作,需要重启.点重启后,系统自动重建桌面进程.控制面板根本无法使用. 下面是网上找到的方法,如果都不行再参照后面我的解决方法. 1. ...

  2. 开源图形数据库Neo4j使用 php开发

    先看看它的示例数据 打开 Neo4j Browser :play movie graph 写代码,然后点play执行 Cypher, the graph query language.Neo4j提供了 ...

  3. Redis未授权访问漏洞

    一.漏洞描述和危害  Redis因配置不当可以未授权访问,被攻击者恶意利用.攻击者无需认证访问到内部数据,可能导致敏感信息泄露,黑客也可以恶意执行flushall来清空所有数据. 攻击者可通过EVAL ...

  4. MySql: ”Commands out of sync“Error (Connect/C++)

    使用 Connector/C++ 查询 Mysql , 连续调用存储过程时 会出现如下: Commands out of sync; you can't run this command now,st ...

  5. 利用VBA宏批量解决Word中图片大小、居中设置

    需求:经常阅读网上的研报(没钱买排版漂亮的高质量研报),有些需要保存的复制下来到word里,图片很大都超出word的边界了,也没有居中,手工一张张调整不现实,上百页的研报,几十张图片. 解决方案:利用 ...

  6. e651. 列出所有可用字体

    A font family refers to a set of font faces with a related typographic design. For example, the font ...

  7. 【Java面试题】29 设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。

    本题并不难,实现方式有很多种,有很多种结构. 方法一:利用内部类实现,两个实现加减的类实现Runnable接口,然后再实现4个具体线程. 代码: public class ManyThreads { ...

  8. Spring-更多DI的知识

    3.3.1 延迟初始化Bean 延迟初始化也叫做惰性初始化,指不提前初始化Bean,而是只有在真正使用时才创建及初始化Bean. 配置方式很简单只需在<bean>标签上指定 “lazy-i ...

  9. logging.xml file setfile(null,true) call failed

    定义目录三个方法:一:${catalina.base}或${catalina.home}相对路径配置方法.catalina.home是你配置服务器时自动在环境变量中加的路径,默认是指向tomcat服务 ...

  10. 不定义JQuery插件 不要说会JQuery

    二.普及JQuery知识 知识1:用JQuery写插件时,最核心的方法有如下两个: $.extend(object) 可以理解为JQuery 添加一个静态方法. $.fn.extend(object) ...