上海建设局网站,wordpress转换成dede,phpcms获取网站访问量,濮阳网站设计公司文章目录Java中的文件操作File常用构造方法方法文件内容的读写——数据流InputStreamFileInputStream利用Scanner进行字符读取OutputStreamPrintWriter按字符读取文件(FileReader)练习代码实例如何按字节进行数据读如何按字节进行数据写如何按字符进行数据读如何按字符进行数据…
文章目录Java中的文件操作File常用构造方法方法文件内容的读写——数据流InputStreamFileInputStream利用Scanner进行字符读取OutputStreamPrintWriter按字符读取文件(FileReader)练习代码实例如何按字节进行数据读如何按字节进行数据写如何按字符进行数据读如何按字符进行数据写Java中的文件操作 在Java中一般谈到文件都是指一个存在磁盘上的文件(狭义的文件)抛开Java站在系统的角度来看操作系统在管理很多软件资源和硬件设备的时候都是把这些东西抽象成了一个一个的文件了这也是系统中典型的一切皆文件的思想。 狭义的文件可以分为两类 普通文件目录文件(文件夹) 在Java标准库java.io下提供了一个File类来对文件(包括目录)进行了抽象描述注意有File对象并不表示File对象的文件一定存在。 
File 
常用构造方法 
构造方法说明File(File parent,String child)根据父目录  孩子文件路径创建一个新的 File 实例File(String pathname)根据文件路径创建一个新的 File 实例路径可以是绝对路径或者相对路径File(String parent,String child)根据父目录  孩子文件路径创建一个新的 File 实例父目录用路径表示
绝对路径可以简单理解为带有盘符的 
相对路径基于当前位置的路径一般以 . 或 … 开头.\表示当前路径…\表示上一级路径 
方法 
返回值类型方法名说明StirnggetParent()返回 File 对象的父目录文件路径StringgetName()返回 FIle 对象的纯文件名称StringgetPath返回 File 对象的文件路径StringgetAbsolutePath()返回 File 对象的绝对路径StringgetCanonicalPath()返回 File 对象的修饰过的绝对路径booleanexists()判断 File 对象描述的文件是否真实存在booleanisDirectory()判断 File 对象代表的文件是否是一个目录booleanisFile()判断 File 对象代表的文件是否是一个普通文件booleancreateNewFile()根据 File 对象自动创建一个空文件。成功创建后返回 truebooleandelete()根据 File 对象删除该文件。成功删除后返回 truebooleandeleteOnExit()根据 File 对象标注文件将被删除删除动作会到JVM 运行结束时才会进行String[]list返回 File 对象代表的目录下的所有文件名File[]listFiles()返回 File 对象代表的目录下的所有文件以 File 对象表示booleanmkdir()创建 File 对象代表的目录booleanmkdirs()创建 File 对象代表的目录如果必要会创建中间目录booleanrenameTo(File dest)进行文件改名也可以视为我们平时的剪切、粘贴操作booleancanRead()判断用户是否对文件有可读权限booleananWrite()判断用户是否对文件有可写权限所谓的文件移动(剪切粘贴),对于操作系统来说其实是一个非常高效的操作。每个文件都有个属性这个属性里就包括了文件的路径移动操作其实只是修改了文件的路径属性而已。 所谓的文件复制(复制粘贴)对于操作系统来说很可能是一个非常低效的操作。就需要把文件的内容都读读出来然后再拷贝一份写入磁盘中。如果文件比较大复制粘贴的开销就比较大了 经典面试题 
给你一个list方法如何遍历一个目录中所有的文件(包含子目录中的文件) 
public class TestDemo {private static ListString result  new ArrayList();public static void printAllFile(String path) {File file  new File(path);//判读这个路径是否真实存在if (file.exists()) {File[] files  file.listFiles();for (File f : files) {//如果是普通文件if (f.isFile()) {result.add(f.getName());} else if (f.isDirectory()) {//如果是目录文件printAllFile(f.getPath());} else {//其它文件..(管道)}}}}public static void main(String[] args) {printAllFile(./);for (String s : result) {System.out.println(s);}}
}文件内容的读写——数据流 在Java标准库中读写文件相关的类有很多。 InputStream/FileInputStream 文件读取操作按照字节为单位进行读文件 OutputStream/FileOutputStream 文件写入操作按照字节为单位进行写文件 InputStream 
返回值类型方法名说明intread()读取一个字节的数据以整数形式放回返回-1代表已经读取完了intread(byte[] b)最多读取 b.length 字节的数据到 b 中,返回实际读取到的数量返回-1代表已经读取完了intread(byte[] b,int off,int len)最多读取 len - off 个字节的数据到 b 中放在从off开始返回实际读取的数量-1代表已经读取完毕voidclose()关闭字节流
注意使用流对象读写完文件之后一定要及时关闭如果没有关闭就可能造成资源泄露 
FileInputStream 
构造方法说明FileInputStream(File file)利用 File 构造文件输入流FileInputStream(String name)利用文件路径构造文件输入流
public class Main {public static void main(String[] args) throws IOException {//这种写法更好try (InputStream inputStream  new FileInputStream(.\\.\\.\\test.txt)) {while (true) {int len  inputStream.read();if (len  -1) {break;}System.out.printf(%c,len);}}catch (IOException e) {e.printStackTrace();}}public static void main1(String[] args) throws IOException {InputStream inputStream  null;try {//创建实例就相当与在打开文件inputStream  new FileInputStream(./././test.txt);//通过逐个字节的方式把文件内容读取出来while (true) {//read无参版本默认每次读取一个字节//无参版本的read。返回值就是每次读取的字节//这个返回值就是 0~255int len  inputStream.read();//如过读到文件末尾(EOF)就会返回 -1if (len  -1) {break;}System.out.printf(%c,len);}} catch (IOException e) {e.printStackTrace();}finally {try {//关闭inputStream.close();} catch (IOException e) {e.printStackTrace();}}}
}InputStream只是一个抽象类要使用还需要具体的实现类关于InputStream实现类有很多基本可以认为不同的输入设备上都可以对应一个InputStream类我们现在只关心从文件中读取所有使用FileInputStream。它继承于InputStream。 注意如果FileInputStream的创建写到 try()的括号里就不需要手动close了等代码执行完毕后会自动close.只要实现了Closeable接口就可以放到try里. 
还可以利用byte数组来读取文件内容 
public static void main(String[] args) {try (InputStream inputStream  new FileInputStream(./././test.txt)) {while (true) {byte[] bytes  new byte[1024];int len  inputStream.read(bytes);if (len  -1) {break;}String s  new String(bytes,0,len);System.out.println(s);}} catch (IOException e) {e.printStackTrace();}}利用Scanner进行字符读取 
上面的读取方法直接使用InputStream进行读取是比较麻烦的这个时候就可以使用常用的Scanenr类来进行读取 
构造方法说明Scanner(InputStream is, String charset)使用 charset 字符集进行 is 的扫描读取
public static void main(String[] args) {//如果要从文件读取出中文借出 Scanner 就可以从文件中读取try (InputStream inputStream  new FileInputStream(./././test.txt)){//这中写法就不用调用 Scanner的 close 方法try (Scanner sc  new Scanner(inputStream,utf-8)) {while (sc.hasNext()) {String str  sc.next();System.out.print(str);}}} catch (IOException e) {e.printStackTrace();}}OutputStream 
返回值方法说明voidwrite(int b)文件写入指定字节数据voidwrite(byte[] b)将b这个字符数组中的全部数据写入输出流中intwrite(byte[] b,int off,int len)将 b 这个字符数组中从 off 开始的数据写入 输出流中一共写 len 个voidclose()闭此输出流并释放与此流相关联的任何系统资源voidfluch()强制刷新缓冲区我们知道I/O的速度是很慢的所以大多的OutputStream为了减少设备操作的次数为了提高效率就可以减少直接访问磁盘的次数。使用缓冲区就能很好的解决这个问题。 缓冲区其实是一段内存空间(这个内存是OutputStream里自带的)当我们使用write方法来写数据的时候并不是直接把数据写到磁盘上而是先放到缓冲区(内存中)如果缓冲区满了或者手动调用flush猜真的会把数据写到磁盘上。 内存和磁盘之间的缓冲区往往是一个内存空间 CPU和内存之间其实也有缓冲区(L1,L2,L3,cache) 代码实例 
public static void main(String[] args) {//一旦按照 OutputStream 的方式打开文件就会把文件的原来的内容给清空try (OutputStream outputStream  new FileOutputStream(./././test.txt)) {/* 写入一个字符outputStream.write(h);outputStream.write(e);*///按照字节来写入byte[] buffer  new byte[] {a,b,c,d};//outputStream.write(buffer);//按照字符串来写入String s  你好世界 ;//将String 转换成 byte数组,指定字符串为 UTF-8outputStream.write(s.getBytes(UTF-8));//刷新缓冲区outputStream.flush();}catch (IOException e) {e.printStackTrace();}}PrintWriter 
PrintWriter 类中提供了我们熟悉的 print/println/printf 方法 
public static void main(String[] args) {try (OutputStream outputStream  new FileOutputStream(./././test.txt)) {//利用 PrintWriter 类来包装一下 OutputStream 然后可以更方便的进行读写try (PrintWriter writer  new PrintWriter(outputStream)) {writer.println(这是第一行);writer.println(这是第二行);writer.println(200300);writer.println(这一行是数字1024);}outputStream.flush();}catch (IOException e) {e.printStackTrace();}}按字符读取文件(FileReader) 
public static String readFile(String filePath) {StringBuilder result  new StringBuilder();try (FileReader fileReader  new FileReader(filePath)) {while (true) {//返回的是一个字符但是不可能有负数,用int才能装下int ch  fileReader.read();if (ch  -1) {break;}result.append((char)ch);}} catch (IOException e) {e.printStackTrace();}return result.toString();}练习 
练习1指定一个目录扫描这个目录找到文件名中包含了指定字符的文件.并提示用户是否要删除这个文件根据用户的输入决定是否删除. 
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
//指定一个目录扫描这个目录找到文件名名中包含了指定字符的文件,并让用户选择是否要删除文件
public class TestDemo1 {public static void main(String[] args) {Scanner sc  new Scanner(System.in);System.out.print(请输入一个绝对路径 - );String rootPath  sc.next();//判断该路径是否存在File fileDir  new File(rootPath);if (!fileDir.exists()) {System.out.println(你输入的路径不正确程序退出);}//输入要查找的一个关键字System.out.println(请输入一个查找的关键字:);String keyWord  sc.next();//递归查找ListFile results  new ArrayList();KeyWordFindFile(fileDir,keyWord,results);//遍历结果判断是否需要删除for (File file : results) {System.out.println(是否删除文件(Y/N)file.getName());String input  sc.next();if (input.equals(Y)) {file.delete();System.out.println(删除成功);}}}/*** 递归查找文件名中包含关键字的文件* param rootPath File对绝对路径* param fileNameKeyWord 查找的关键字* param result list*/private static void KeyWordFindFile(File rootPath,String fileNameKeyWord,ListFile result) {File[] files  rootPath.listFiles();for (File file : files) {if (file.isDirectory()) {//如果是目录就递归KeyWordFindFile(file,fileNameKeyWord,result);} else if (file.isFile()) {//判断文件名是否包含关键字if (file.getName().contains(fileNameKeyWord)) {result.add(file);}}}}
}练习2把文件复制到指定目录下 
//把指定文件复制到另外一个路径一定是文件public static void main(String[] args) throws IOException {System.out.print(请输要复制文件的绝对路径 - );Scanner sc  new Scanner(System.in);String originalPath  sc.next();//判断是否是文件File originalFile  new File(originalPath);if (!originalFile.isFile()) {System.out.println(输入文件绝对路径错误程序退出);return;}System.out.print(请输入文件要复制到的绝对路径(指定文件名) - );String targetPath  sc.next();File targetFile  new File(targetPath);//判断文件是否已经存在if (targetFile.exists()) {System.out.println(文件已存在是否替换(Y/N));String input  sc.next();if (input.equals(N)) {System.out.println(复制取消);return;}}//开始复制try (InputStream inputStream  new FileInputStream(originalFile);OutputStream outputStream  new FileOutputStream(targetFile)) {//一次性最多读取1024个字节byte[] bytes  new byte[1024];while (true) {int len  inputStream.read(bytes);if (len  -1) {break;}//读多少写多少outputStream.write(bytes,0,len);}//不flush也是可以的在close后会自动flushoutputStream.flush();} catch (IOException e) {e.printStackTrace();}System.out.println(复制成功);}练习3扫描指定目录并找到 名称 或者内容中包含指定 字符 的所有普通文件不包含目录 
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;public class TestDemo3 {//扫描指定目录并找到 名称 或者内容中包含指定 字符 的所有普通文件不包含目录public static void main(String[] args) {Scanner sc  new Scanner(System.in);System.out.print(请输入一个指定目录的绝对路径 - );String path  sc.next();File dirPath  new File(path);if (!dirPath.isDirectory()) {System.out.println(你输入的绝对路径不是一个目录。程序自动退出);return;}System.out.print(请输入一个要查找的关键字 - );String keyWord  sc.next();//递归遍历目录下的所有文件ListFile result  new ArrayList();getAllFile(dirPath,result,keyWord);for (File file : result) {System.out.println(file.getName());}}private static void getAllFile(File dirPath,ListFile result,String keyWord) {File[] files  dirPath.listFiles();if (files  null || files.length  0) {return;}for (File file : files) {if (file.isDirectory()) {getAllFile(file,result,keyWord);} else if (file.isFile()) {//如果是文件就判断是否包含关键字if(containKeywords(file,keyWord)) {result.add(file);}}}}//判断文件内容是否包含关键字 keyWordprivate static boolean containKeywords(File file,String keyWord) {StringBuilder stringBuilder  new StringBuilder();//使用 Scanner 以UTF-8字符集读取try (InputStream inputStream  new FileInputStream(file);Scanner scanner  new Scanner(inputStream,UTF-8)) {while (scanner.hasNext()) {String s  scanner.nextLine();stringBuilder.append(s);}} catch (IOException e) {e.printStackTrace();}return stringBuilder.indexOf(keyWord) ! -1;}
}代码实例 
如何按字节进行数据读 
try (InputStream input  new ...) {byte[] bytes  new byte[1024];while (true) {int len  input.read(bytes);if (len  -1) {break;}//0到len表示bytes读到的数据String reslult  new String(bytes,0,len);}
}如何按字节进行数据写 
try (OutputStream output  new ...) {byte[] bytes  new byte[1024];while (/* 还有未完成的业务数据 */) {// 将业务数据填入 buf 中长度为 nint len  ...;output.write(bytes, 0, len);}output.flush();//刷新缓冲区
}如何按字符进行数据读 
try (InputStream is  ...) {try (Scanner scanner  new Scanner(is, UTF-8)) {while (scanner.hasNextLine()) {String line  scanner.nextLine();// 根据 line 做业务处理}}
}如何按字符进行数据写 
try (OutputStream os  ...) {try (OutputStreamWriter osWriter  new OutputStreamWriter(os, UTF-8)) {try (PrintWriter writer  new PrintWriter(osWriter)) {while (/* 还有未完成的业务数据 */) {writer.println(...);}writer.flush(); // 进行数据刷新操作}}
}啥样的类可以放到 try()里实现了 Closeble接口的就可以放入 try()里 
 文章转载自: http://www.morning.rgdcf.cn.gov.cn.rgdcf.cn http://www.morning.dwmtk.cn.gov.cn.dwmtk.cn http://www.morning.lsqxh.cn.gov.cn.lsqxh.cn http://www.morning.bzqnp.cn.gov.cn.bzqnp.cn http://www.morning.rpsjh.cn.gov.cn.rpsjh.cn http://www.morning.coatingonline.com.cn.gov.cn.coatingonline.com.cn http://www.morning.mxxsq.cn.gov.cn.mxxsq.cn http://www.morning.sgtq.cn.gov.cn.sgtq.cn http://www.morning.tlfyb.cn.gov.cn.tlfyb.cn http://www.morning.youprogrammer.cn.gov.cn.youprogrammer.cn http://www.morning.yqwsd.cn.gov.cn.yqwsd.cn http://www.morning.gkmwk.cn.gov.cn.gkmwk.cn http://www.morning.yxyyp.cn.gov.cn.yxyyp.cn http://www.morning.wrtxk.cn.gov.cn.wrtxk.cn http://www.morning.c7627.cn.gov.cn.c7627.cn http://www.morning.bqxxq.cn.gov.cn.bqxxq.cn http://www.morning.sfcfy.cn.gov.cn.sfcfy.cn http://www.morning.rkgyx.cn.gov.cn.rkgyx.cn http://www.morning.lpmdy.cn.gov.cn.lpmdy.cn http://www.morning.kphyl.cn.gov.cn.kphyl.cn http://www.morning.qgghj.cn.gov.cn.qgghj.cn http://www.morning.mbbgk.com.gov.cn.mbbgk.com http://www.morning.eviap.com.gov.cn.eviap.com http://www.morning.kxymr.cn.gov.cn.kxymr.cn http://www.morning.qzsmz.cn.gov.cn.qzsmz.cn http://www.morning.simpliq.cn.gov.cn.simpliq.cn http://www.morning.ptysj.cn.gov.cn.ptysj.cn http://www.morning.rcyrm.cn.gov.cn.rcyrm.cn http://www.morning.zbqry.cn.gov.cn.zbqry.cn http://www.morning.kgphc.cn.gov.cn.kgphc.cn http://www.morning.bqpgq.cn.gov.cn.bqpgq.cn http://www.morning.grzpc.cn.gov.cn.grzpc.cn http://www.morning.btcgq.cn.gov.cn.btcgq.cn http://www.morning.wslr.cn.gov.cn.wslr.cn http://www.morning.tkxyx.cn.gov.cn.tkxyx.cn http://www.morning.snzgg.cn.gov.cn.snzgg.cn http://www.morning.dansj.com.gov.cn.dansj.com http://www.morning.pndhh.cn.gov.cn.pndhh.cn http://www.morning.rhsr.cn.gov.cn.rhsr.cn http://www.morning.lpmlx.cn.gov.cn.lpmlx.cn http://www.morning.pqyms.cn.gov.cn.pqyms.cn http://www.morning.kwnnx.cn.gov.cn.kwnnx.cn http://www.morning.fpkpz.cn.gov.cn.fpkpz.cn http://www.morning.rynq.cn.gov.cn.rynq.cn http://www.morning.jlgjn.cn.gov.cn.jlgjn.cn http://www.morning.rbjf.cn.gov.cn.rbjf.cn http://www.morning.gtdf.cn.gov.cn.gtdf.cn http://www.morning.jnzfs.cn.gov.cn.jnzfs.cn http://www.morning.fdhwh.cn.gov.cn.fdhwh.cn http://www.morning.wyrkp.cn.gov.cn.wyrkp.cn http://www.morning.wyjpt.cn.gov.cn.wyjpt.cn http://www.morning.dhbyj.cn.gov.cn.dhbyj.cn http://www.morning.kdxzy.cn.gov.cn.kdxzy.cn http://www.morning.hxycm.cn.gov.cn.hxycm.cn http://www.morning.qflcb.cn.gov.cn.qflcb.cn http://www.morning.czzpm.cn.gov.cn.czzpm.cn http://www.morning.rjbb.cn.gov.cn.rjbb.cn http://www.morning.gpsrk.cn.gov.cn.gpsrk.cn http://www.morning.kabaifu.com.gov.cn.kabaifu.com http://www.morning.cnbdn.cn.gov.cn.cnbdn.cn http://www.morning.tgfsr.cn.gov.cn.tgfsr.cn http://www.morning.ftrpvh.cn.gov.cn.ftrpvh.cn http://www.morning.rwmft.cn.gov.cn.rwmft.cn http://www.morning.fkwp.cn.gov.cn.fkwp.cn http://www.morning.qbccg.cn.gov.cn.qbccg.cn http://www.morning.rglzy.cn.gov.cn.rglzy.cn http://www.morning.gbnsq.cn.gov.cn.gbnsq.cn http://www.morning.gghhmi.cn.gov.cn.gghhmi.cn http://www.morning.gtkyr.cn.gov.cn.gtkyr.cn http://www.morning.xqcgb.cn.gov.cn.xqcgb.cn http://www.morning.lxhny.cn.gov.cn.lxhny.cn http://www.morning.sypby.cn.gov.cn.sypby.cn http://www.morning.sfdsn.cn.gov.cn.sfdsn.cn http://www.morning.prhqn.cn.gov.cn.prhqn.cn http://www.morning.nxstj.cn.gov.cn.nxstj.cn http://www.morning.rljr.cn.gov.cn.rljr.cn http://www.morning.jstggt.cn.gov.cn.jstggt.cn http://www.morning.yhyqg.cn.gov.cn.yhyqg.cn http://www.morning.tfwg.cn.gov.cn.tfwg.cn http://www.morning.yfmlj.cn.gov.cn.yfmlj.cn