您的位置:首页 > 编程语言 > Java开发

23个常用的文件处理方法

2017-01-22 15:47 288 查看

前言

初学java.io,对流不是很理解,查找了很多关于流的解释,还是觉得下面这段话最通俗易懂:比如你家的水龙头的管道就是一个流:流又分为输入输出流,输入流就是你家水龙头抽水库水的那头(FileInputStream:将水抽到管道里面),输出流就是你家水龙头流到你家大水缸的那头(FileOutputStream:将水流到缸里)。现在有个A.txt文件,你要读取里面的信息,就相当于水龙头抽水库水到管道(FileInputStream),然后读取完后写入到另一个文件里面(FileOutputStream),就是相当于水龙头将抽到水后流到大水缸。

学习io最好的方式就是写工具类,下面列出了工作中常用的方法,有需要的博友请拿走。

1.获取系统的默认编码

/**
*
* 获取系统的默认编码
*
* @return
* @see [类、类#方法、类#成员]
*/
public static String getLocalEncoding()
{

String encoding = System.getProperty("file.encoding");

return encoding;
}


2.在某个路径下创建一个文件

/**
*
* 在某个路径下创建一个文件
*
* @param filePath
* @see [类、类#方法、类#成员]
*/
public static void createFile(String filePath)
{
File f = new File(filePath);

try
{
if (!f.exists())
{

f.createNewFile();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}

3.创建一个文件夹

/**
*
* 创建一个文件夹
*
* @param filePath
* @see [类、类#方法、类#成员]
*/
public static void createDir(String filePath)
{

File f = new File(filePath);

try
{
if (!f.exists())
{
f.mkdir();
}
}
catch (Exception e)
{
e.printStackTrace();
}

}


4.某个路径下如果存在文件,则删除

/**
*
* 某个路径下如果存在文件,则删除
*
* @param filePath
* @see [类、类#方法、类#成员]
*/
public static void deleteFile(String filePath)
{

File f = new File(filePath);

try
{
if (f.exists())
{
f.delete();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}

5.删除文件夹

/**
* 功 能: 删除文件夹
*
* @param strDir 要删除的文件夹名称
* @return 成功true;否则false
*/
public static boolean removeDir(String strDir)
{
File rmDir = new File(strDir);
if (rmDir.isDirectory() && rmDir.exists())
{
String[] fileList = rmDir.list();

for (int i = 0; i < fileList.length; i++)
{
String subFile = strDir + File.separator + fileList[i];
File tmp = new File(subFile);
if (tmp.isFile())
tmp.delete();
else if (tmp.isDirectory())
removeDir(subFile);
}
rmDir.delete();
}
else
{
return false;
}
return true;
}


6.判断指定路径是否为一个文件夹

/**
*
* 判断指定路径是否为一个文件夹
*
* @param filePath
* @return
* @see [类、类#方法、类#成员]
*/
public static boolean isDirectory(String filePath)
{

File f = new File(filePath);
boolean flag = false;

try
{
if (f.isDirectory())
{
flag = true;
}
}
catch (Exception e)
{
e.printStackTrace();
}

return flag;
}


7.列出指定目录的全部文件名

/**
*
* 列出指定目录的全部文件名
*
* @param filePath
* @return
* @see [类、类#方法、类#成员]
*/
public static String[] getFileNameInPath(String filePath)
{

File f = new File(filePath);
String[] list = null;

try
{
if (f.exists())
{
list = f.list();

}
}
catch (Exception e)
{
e.printStackTrace();
}

return list;
}


8.搜索指定目录的全部内容(包括所有子目录)

private static List<File> listFile = new ArrayList<>();

/**
*
* 搜索指定目录的全部内容(包括所有子目录)
*
* @param f
* @return
* @see [类、类#方法、类#成员]
*/
public static List<File> allFilesInPathByFile(File f)
{

if (null != f)
{

if (f.isDirectory())
{
File[] fs = f.listFiles();

if (null != fs)
{
for (File file : fs)
{
// 递归调用
allFilesInPathByFile(file);
}
}

}
else
{

listFile.add(f);

}

}

return listFile;
}


9.字节流,向文件中追加字符串

/**
*
* 字节流,向文件中追加字符串
*
* @param filePath
* @param str
* @throws IOException
* @see [类、类#方法、类#成员]
*/
public static void appendStrByB(String filePath, String str)
throws IOException
{

File f = new File(filePath);

if (f.exists())
{
OutputStream out = new FileOutputStream(f, true);

byte[] bs = str.getBytes();

try
{
out.write(bs);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
out.close();
}
}

}


10.字节流,读取文件内容

/**
*
* 字节流,读取文件内容
*
* @param filePath
* @return
* @throws IOException
* @see [类、类#方法、类#成员]
*/
public static String readNlFileByB(String filePath)
throws IOException
{

File f = new File(filePath);
byte[] bs = null;

if (f.exists())
{
FileInputStream in = new FileInputStream(filePath);
bs = new byte[1024];
int count = 0;
int temp = 0;

while ((temp = in.read()) != (-1))
{
bs[count++] = (byte)temp;
}

in.close();
}

return new String(bs);
}


11.字符流,写入数据

/**
*
* 字符流,写入数据
*
* @param filePath
* @param str
* @throws IOException
* @see [类、类#方法、类#成员]
*/
public static void writeStrByC(String filePath, String str)
throws IOException
{

File f = new File(filePath);

if (f.exists())
{

Writer out = new FileWriter(f);
try
{
out.write(str);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
out.close();
}

}
}


12.字符流,追加字符

/**
*
* 字符流,追加字符
*
* @param filePath
* @param str
* @throws IOException
* @see [类、类#方法、类#成员]
*/
public static void appendStrByc(String filePath, String str)
throws IOException
{

File f = new File(filePath);

if (f.exists())
{

FileWriter out = new FileWriter(f, true);
try
{
out.write(str);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
out.close();
}
}

}


13.字符流,读取内容

/**
*
* 字符流,读取内容
*
* @param filePath
* @return
* @throws IOException
* @see [类、类#方法、类#成员]
*/
public static String readNLFileByC(String filePath)
throws IOException
{

File f = new File(filePath);

FileReader in = new FileReader(f);
char[] cs = null;

try
{
cs = new char[100];

int count = 0;
int temp = 0;

while ((temp = in.read()) != (-1))
{
cs[count++] = (char)temp;
}
}
catch (Exception e)
{

e.printStackTrace();
}
finally
{

in.close();
}

return new String(cs);
}


14.拷贝文件并显示进度(只能拷贝文件)

/**
* 功 能: 拷贝文件并显示进度(只能拷贝文件)
*
* @param strSourceFileName 指定的文件全路径名
* @param strDestDir 移动到指定的文件夹
* @return 成功true;否则false
*/
public static boolean copyTo(String strSourceFileName, String strDestDir)
{
File fileSource = new File(strSourceFileName);
File fileDest = new File(strDestDir);

// 如果源文件不存或源文件是文件夹
if (!fileSource.exists() || !fileSource.isFile())
{
System.out.println("源文件[" + strSourceFileName + "],不存在或是文件夹!");
return false;
}

// 如果目标文件夹不存在
if (!fileDest.isDirectory() || !fileDest.exists())
{
if (!fileDest.mkdirs())
{
System.out.println("目录文件夹不存,在创建目标文件夹时失败!");
return false;
}
}

try
{
String strAbsFilename = strDestDir + File.separator + fileSource.getName();

FileInputStream fileInput = new FileInputStream(strSourceFileName);
FileOutputStream fileOutput = new FileOutputStream(strAbsFilename);

System.out.println("开始拷贝文件");

int count = -1;

long nWriteSize = 0;
long nFileSize = fileSource.length();

byte[] data = new byte[1024];

while (-1 != (count = fileInput.read(data, 0, 1024)))
{

fileOutput.write(data, 0, count);

nWriteSize += count;

long size = (nWriteSize * 100) / nFileSize;
long t = nWriteSize;

String msg = null;

if (size <= 100 && size >= 0)
{
msg = "\r拷贝文件进度:   " + size + "%   \t" + "\t   已拷贝:   " + t;
System.out.println(msg);
}
else if (size > 100)
{
msg = "\r拷贝文件进度:   " + 100 + "%   \t" + "\t   已拷贝:   " + t;
System.out.println(msg);
}

}

fileInput.close();
fileOutput.close();

System.out.println("拷贝文件成功!");
return true;

}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}


15.COPY文件

/**
* COPY文件
*
* @param srcFile String
* @param desFile String
* @return boolean
*/
public static boolean copyToFile(String srcFile, String desFile)
{
File scrfile = new File(srcFile);
if (scrfile.isFile() == true)
{
int length;
FileInputStream fis = null;
try
{
fis = new FileInputStream(scrfile);
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
File desfile = new File(desFile);

FileOutputStream fos = null;
try
{
fos = new FileOutputStream(desfile, false);
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
desfile = null;
length = (int)scrfile.length();
byte[] b = new byte[length];
try
{
fis.read(b);
fis.close();
fos.write(b);
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
scrfile = null;
return false;
}
scrfile = null;
return true;
}


16.COPY文件夹

/**
* COPY文件夹
*
* @param sourceDir String
* @param destDir String
* @return boolean
*/
public static boolean copyDir(String sourceDir, String destDir)
{
File sourceFile = new File(sourceDir);
String tempSource;
String tempDest;
String fileName;
File[] files = sourceFile.listFiles();
for (int i = 0; i < files.length; i++)
{
fileName = files[i].getName();
tempSource = sourceDir + "/" + fileName;
tempDest = destDir + "/" + fileName;
if (files[i].isFile())
{
copyToFile(tempSource, tempDest);
}
else
{
copyDir(tempSource, tempDest);
}
}
sourceFile = null;
return true;
}


17.删除指定的文件

/**
* 功 能: 删除指定的文件 参 数: 指定绝对路径的文件名 strFileName 返回值: 如果删除成功true否则false;
*
* @param strFileName
* @return
*/
public static boolean delete(String strFileName)
{
File fileDelete = new File(strFileName);

if (!fileDelete.exists() || !fileDelete.isFile())
{
System.out.println(strFileName + "不存在!");
return false;
}

return fileDelete.delete();
}


18.移动文件(只能移动文件)

/**
* 功 能: 移动文件(只能移动文件)
*
* @param strSourceFileName 指定的文件全路径名
* @param strDestDir 移动到指定的文件夹中
* @return 成功true; 否则false
*/
public static boolean moveFile(String strSourceFileName, String strDestDir)
{
if (copyTo(strSourceFileName, strDestDir))
return delete(strSourceFileName);
else
return false;
}


19.本地下载

/**
*
* 本地下载
* @param fileName
* @param filePath
* @param request
* @param response
* @throws IOException
* @see [类、类#方法、类#成员]
*/
public static void fileDownload(String fileName, String filePath, HttpServletRequest request,
HttpServletResponse response)
throws IOException
{
OutputStream os = response.getOutputStream();
try
{
transNameSetHeader(request, response, fileName);
File file = new File(filePath);
os.write(org.apache.commons.io.FileUtils.readFileToByteArray(file));
os.flush();
}
catch (Exception e)
{
System.out.println("文件下载时异常!!!");
System.out.println("异常:"+e.getMessage());
}
finally
{
if (os != null)
{
os.close();
}
}
}


20.网络下载

/**
*
* 网络下载
* @param request
* @param response
* @param fileName
* @param url
* @throws MalformedURLException
* @see [类、类#方法、类#成员]
*/
public static void downloadNet(HttpServletRequest request, HttpServletResponse response, String fileName,
String url)
throws MalformedURLException
{
int bytesum = 0;
int byteread = 0;

URL urls = new URL(url);
try
{
URLConnection conn = urls.openConnection();
InputStream inStream = conn.getInputStream();
OutputStream fs = response.getOutputStream();
transNameSetHeader(request, response, fileName);
byte[] buffer = new byte[1204];
int length;
while ((byteread = inStream.read(buffer)) != -1)
{
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}


21.根据文件头判断请求来自的浏览器

/**
* Desc:根据文件头判断请求来自的浏览器,以便有针对性的对文件名转码
*
* @param request
* @return
* @throws Exception
*/
public static String transNameSetHeader(HttpServletRequest request,HttpServletResponse response,String fileName)
{

String agent = request.getHeader("USER-AGENT");
// fileName = fileName.trim(); //去首尾空格
try
{
// 根据文件头判断请求来自的浏览器,以便有针对性的对文件名转码
if (null != agent && -1 != agent.indexOf("theworld"))
{ // 世界之窗
fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1"); // 解决下载的文件名中含有小括号转变义符%28%29
}
else if (null != agent && -1 != agent.indexOf("MSIE 8.0"))
{ // IE8
String lenFileName = URLEncoder.encode(fileName, "UTF-8");
if (lenFileName.length() > 150)
{ // 文件名长度是否大于150个字符
fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
}
else
{
fileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
}
}
else if (null != agent && -1 != agent.indexOf("MSIE 7.0") && -1 != agent.indexOf("SE 2.X MetaSr 1.0"))
{ // sogo浏览器
fileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
}
else if (null != agent && (-1 != agent.indexOf("SV1") || -1 != agent.indexOf("360SE")))
{ // 360安全浏览器
String lenFileName = URLEncoder.encode(fileName, "UTF-8");
if (lenFileName.length() > 150)
{ // 文件名长度是否大于150个字符
fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
}
else
{
fileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
}
}
else if (null != agent && -1 != agent.indexOf("Chrome"))
{ // google
fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1"); // 解决下载的文件名中含有小括号转变义符%28%29
}
else if (null != agent && -1 != agent.indexOf("Firefox"))
{ // Firefox
fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
}
else if (null != agent && -1 != agent.indexOf("Safari"))
{ // Firefox
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
}
else
{ // 其它浏览器
fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
}

response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
}
catch (Exception e)
{
throw new RuntimeException("transFileName error", e);
}
return fileName;
}


22.按行读取txt文件的内容

/**
* 功能:按行读取txt文件的内容
* 步骤:1:先获得文件句柄
* 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
* 3:读取到输入流后,需要读取生成字节流
* 4:一行一行的输出。readline()。
* 备注:需要考虑的是异常情况
* @param filePath
*/
public static void readTxtFile(String filePath,String encoding){

try {
File file=new File(filePath);
String lineTxt="";
if(file.isFile() && file.exists()){ //判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file),encoding);//考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
while((lineTxt = bufferedReader.readLine()) != null){

System.out.println(lineTxt);
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
} catch (Exception e) {

e.printStackTrace();
}

}


23.按行写入txt文件

/**
*
* 按行写入txt文件
* @param filePath
* @see [类、类#方法、类#成员]
*/
public static void writeTxtFile(String filePath){
FileWriter fw = null;
try {
fw = new FileWriter(filePath,true);
String c = "abs"+"\r\n";
fw.write(c);
fw.close();
} catch (IOException e1) {
e1.printStackTrace();
System.out.println("写入失败");
System.exit(-1);
}
}


下载资源

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java.io javaweb