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. Hive中如何添加自定义UDF函数以及oozie中使用hive的自定义函数

    操作步骤: 1. 修改.hiverc文件 在hive的conf文件夹下面,如果没有.hiverc文件,手工自己创建一个. 参照如下格式添加: add jar /usr/local/hive/exter ...

  2. javascript商务通

    //左侧就医服务新 document.write("<style type='text/css'>"); document.write(".left_swt{ ...

  3. 为什么手机无法执行应用? Values之谜

    欢迎Follow我的GitHub, 关注我的CSDN, 精彩不断! CSDN: http://blog.csdn.net/caroline_wendy/article/details/68923156 ...

  4. ORACLE11G 字符集更改(这里更改为AL32UTF8)

    ORACLE11G 字符集更改(这里更改为AL32UTF8)更改步骤:1.用sysdba角色用户登录sqlplus: 命令行输入:sqlplus sys as sysdba 2.输入口令,进入sqlp ...

  5. iOS边练边学--应用数据存储的常用方式(plist,Preference,NSKeyedArchiver)其中的三种

    iOS应用数据存储的常用方式: XML属性列表(plist)归档 Preference(偏好设置) NSKeyedArchiver归档(NSCoding) SQLite3--这里暂且不讲 Core D ...

  6. 轻量级ORM框架Dapper应用六:Dapper支持存储过程

    在Entity Framework中讲解了EF如何支持存储过程,同样,Dapper也支持存储过程,只需要在Query()方法的CommandType中标记使用的是存储过程就可以了.在Users表上面创 ...

  7. 解决ssh连接超时时间(ssh timeout)的设置方法

    本文介绍下,linux中ssh连接超时时间的设置方法,以避免总是被强行退出.有需要的朋友,参考下吧.有关修改ssh连接超时时间的方法,网上介绍的很多了.比如下面这个:可以减少ssh连接超时等待的时间: ...

  8. java web中读取properties文件时的路径问题

    在web开发时,难免会有一些固定的参数,我们一般把这些固定的参数存在properties文件中,然后用的时候要读出来.但经常出现一些错误,找不到相应的路径,所以,今天特地讲一些如何正确获得路径. 首先 ...

  9. r语言 包说明

    [在实际工作中,每个数据科学项目各不相同,但基本都遵循一定的通用流程.具体如下]   [下面列出每个步骤最有用的一些R包] 1.数据导入以下R包主要用于数据导入和保存数据:feather:一种快速,轻 ...

  10. firefox插件之 vimperator 的使用

    简介: vimperator 是 Firefox浏览器下的一个插件,可以让我们像使用vim 一样使用 firefox浏览器,高效畅快,不用鼠标了.它的官网为:http://www.vimperator ...