1. 文件过滤器

public class Main {public static void main(String[] args) throws IOException {File file = new File("/home/test/");String [] nameList = file.list(new FilenameFilter() {   //文件过滤器 @Overridepublic boolean accept(File dir, String name) {// TODO Auto-generated method stub              return name.endsWith(".png")  || new File(name).isDirectory();  //后缀名"png", 或者是目录}});for(String str : nameList ){System.out.println(str);}       }
}

2. 整理

// * write by kevin, 2013/7/8import java.io.*;public class IO_test {public boolean IsExist(String fileName){ //文件是否存在File file = new File(fileName);if( file.exists() ){System.out.println("Is file: " + file.isFile());System.out.println("Filename is: " + file.getName());System.out.println("Path is: " + file.getPath());System.out.println("AbsolutePath " + file.getAbsolutePath());System.out.println("Parent dir is: " + file.getParent());System.out.println("File size is: " + file.length() + " bytes");return true;}else{return false;}  }public boolean CreateFile(String fileName) throws IOException{ //创建文件  File file = new File(fileName);  if( file.exists() ){System.out.println(fileName + " File has existed");return false;}else{file.createNewFile();   return true;}  }public boolean CreateDir(String dirName){ //创建目录File file = new File(dirName);if( file.exists() ){System.out.println(dirName + " Dir has existed");return false;}else{file.mkdirs();return true;}  }public void WriteByByte(String fileName, String str) throws IOException{ //以字节流写文件  File file = new File(fileName);if( !file.exists() ){System.out.println(fileName + " File doesn't exist");   file.createNewFile();System.out.println(fileName + " File has created");}FileOutputStream fo = new FileOutputStream(file);byte [] content = str.getBytes();fo.write(content);fo.close();}public String ReadByByte(String fileName) throws IOException{ //以字节流读文件File file = new File(fileName);if ( file.exists() ){   FileInputStream fi = new FileInputStream(file);byte [] content = new byte[fi.available()];fi.read(content);   String str = new String(content);System.out.println("Read file: " + str.trim());fi.close();return str.trim();}else{System.out.println("File doesn't exist");return "File doesn't exist";}}public String ReadByBuffer(String fileName) throws IOException{ //以缓存的方式读文件 File file_temp = new File(fileName);if ( file_temp.exists() ){FileReader file = new FileReader(fileName);BufferedReader br = new BufferedReader(file);StringBuffer str = new StringBuffer();String sw = br.readLine();while( sw != null ){str.append(sw + "\n");sw = br.readLine();}System.out.println("Read file: " + str);return str.toString();}else{System.out.println("File doesn't exist");return "File doesn't exist";}}public void WriteByBuffer(String fileName, String str) throws IOException{ //以缓存方式写文件File file_temp = new File(fileName);if ( !file_temp.exists() ){System.out.println(fileName + " File doesn't exist");   file_temp.createNewFile();System.out.println(fileName + " File has created");}FileWriter file = new FileWriter(fileName);BufferedWriter bw = new BufferedWriter(file);bw.write(str);bw.close();}public boolean DeleteFile(String fileName){ //删除文件File file = new File(fileName);if( file.exists() ){System.out.println("Will delete file: " + fileName);if( file.delete() ){System.out.println("Have deleted file");return true;}    else{System.out.println("Deleted file fail");return false;}}else{System.out.println("File doesn't exist");return false;} }public boolean CopyFileByByte(String fileName1, String fileName2) throws IOException{ //以字节流 复制文件File file = new File(fileName1);if( !file.exists() ){System.out.println(fileName1 + " File doesn't exist");return false;}FileInputStream fi = new FileInputStream(file);byte [] content = new byte[fi.available()];fi.read(content);fi.read(content, 0, content.length);String str = new String(content);  File file_other =new File(fileName2);if( !file_other.exists() ){System.out.println(fileName2 + "File doesn't exist");file_other.createNewFile();System.out.println(fileName2 + "File has created");}FileOutputStream fo = new FileOutputStream (file_other,true);fo.write(content);fo.flush();fo.close();fi.close();  return true;}public boolean CopyFileByBuffer(String fileName1, String fileName2) throws IOException{ //以缓存方式复制文件File file_temp = new File(fileName1);if( !file_temp.exists() ){System.out.println(fileName1 +  "File doesn't existed");return false;}file_temp = new File(fileName2);if( !file_temp.exists() ){System.out.println(fileName2 +  "File doesn't existed");file_temp.createNewFile();System.out.println(fileName2 +  "File has created");}FileReader file = new FileReader(fileName1);BufferedReader br = new BufferedReader(file);String str = br.readLine();  FileWriter file_other = new FileWriter(fileName2);BufferedWriter bw = new BufferedWriter(file_other);while( str!=null ){bw.write(str);bw.newLine();str = br.readLine();}bw.flush();bw.close();br.close();return false;} }

3. 重定义标准输入输出, 标准输入输出为键盘和屏幕,但是这些都可以自己重定义 为 文件 或其他

                  PrintStream ps = null;      try {ps = new PrintStream(new FileOutputStream("/home/test/123.txt"));System.setOut(ps);  //重定义标准输出到 文件123.txtSystem.out.println("123456789"); }catch (IOException e){e.printStackTrace();}finally {ps.close();}
                  FileInputStream fis = null;try{fis = new FileInputStream("/home/test/123.txt");         System.setIn(fis);  //重定义标准输入为 文件123.txtScanner sc = new Scanner(System.in);sc.useDelimiter("\n");       while(sc.hasNext()){System.out.println(sc.next());}}catch(IOException e){e.printStackTrace();}finally{fis.close();}

3. RandomAccessFile 读写文件, 可以操控指针,做到追加和插入文件内容。

public class Main {public static void main(String[] args) throws IOException  {RandomAccessFile raf = null;try{raf = new RandomAccessFile("/home/test/123.txt", "rw");System.out.println("point at: " + raf.getFilePointer());raf.seek(5);System.out.println("point at: " + raf.getFilePointer());byte[] buf = new byte[512];int hasRead = 0;while( (hasRead=raf.read(buf)) > 0 ){System.out.println(new String(buf, 0, hasRead));}System.out.println("point at: " + raf.getFilePointer());raf.write("add into file\n".getBytes());}catch (IOException e){e.printStackTrace();}finally{raf.close();}}
}

4. 保存对象到文件, 对象序列化和反序列化

当使用Java序列化机制序列化可变对象时一定要要注意,只有当第一次调用writeObject方法来输出对象时才会将对象转为字节序列,第二次只会存入一个序列化编号。

class Person implements java.io.Serializable  //序列化的类 需要实现Serializable接口
{private String name;private int age;public Person(String name, int age){this.name = name;this.age = age;}int getAge(){return this.age;}String getName(){return this.name;}
}public class Main {public static void main(String[] args){ObjectOutputStream oos = null;ObjectInputStream ois = null;try{oos = new ObjectOutputStream(new FileOutputStream("/home/test/object.txt")); //对象输入流Person per = new Person("kevin", 11);oos.writeObject(per);   //将对象写入流try{oos.close();}catch( IOException e ){e.printStackTrace();}ois = new ObjectInputStream(new FileInputStream("/home/test/object.txt")); //对象反序列Person p = (Person)ois.readObject();  //反序列System.out.println("Get object from file, name: " + p.getName() + " age: " + p.getAge());}catch (IOException e){e.printStackTrace();}catch (ClassNotFoundException e) {e.printStackTrace();}finally{try{ois.close();}catch( IOException e ){e.printStackTrace();}}}
}

5. 文件锁

FileOutputStream fos = new FileOutputStream("file.txt");

FileChannel fc = fos.getChannel(); //获取FileChannel对象
FileLock fl = fc.tryLock();  //or fc.lock();
if(null != fl)
System.out.println("You have got file lock.");
//TODO write content to file
//TODO write end, should release this lock
fl.release(); //释放文件锁  注意:释放锁要在文件写操作之前,否则会出异常
fos.close;  //关闭文件写操作

转载于:https://www.cnblogs.com/xj626852095/p/3648173.html

Java -- IO相关推荐

  1. Java IO 流 学习 总结

    I/O  主要是对文件进行处理, 其主要包含3个方面的内容 1 input 输入 2 out 出入 3 File 文件 Java 流的概念 流是一组有序的数据序列,流提供了一条通道程序,可以是这条通道 ...

  2. Java基础(二十七)Java IO(4)字符流(Character Stream)

    字符流用于处理字符数据的读取和写入,它以字符为单位. 一.Reader类与Writer类 1.Reader类是所有字符输入流的父类,它定义了操作字符输入流的各种方法. 2.Writer类是所有字符输出 ...

  3. Java IO流学习总结四:缓冲流-BufferedReader、BufferedWriter

    Java IO流学习总结四:缓冲流-BufferedReader.BufferedWriter 转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/det ...

  4. java openfile busy_android java.io.IOException: open failed: EBUSY (Device or resource busy)

    今天遇到一个奇怪的问题, 测试在程序的下载界面,下载一个文件第一次下载成功,删除后再下载结果下载报错, 程序:file.createNewFile(); 报错:java.io.IOException: ...

  5. java.io.file jar_IDEA Maven 打包运行 jar java.io.FileNotFoundException: 问题?

    java.io.FileNotFoundException: D:\workspaceIdea\ywjc-refactor\target\lib\javax.annotation-api-1.3.2. ...

  6. Java IO流学习总结三:缓冲流-BufferedInputStream、BufferedOutputStream

    Java IO流学习总结三:缓冲流-BufferedInputStream.BufferedOutputStream 转载请标明出处:http://blog.csdn.net/zhaoyanjun6/ ...

  7. Java IO系列之字节流拷贝文件性能比较

    Java IO 字节流基类 InputStream--输入流, OutPutStream--输出流, 输入流用于读,输出流用于写. 字节流默认一次只读取或输出一个字节. package jonavin ...

  8. java io在文件结尾持续添加内容

    [代码] java io在文件结尾持续添加内容 public static void write(String path, String content) {try {File f = new Fil ...

  9. java.io包对象读写_java.io 包中的____________和____________类主要用于对对象(Object)的读写_学小易找答案...

    [多选题]连铸钢水成分控制的要求有( ). [单选题]起动机用直流电动机将电能转化为 [单选题]下列关于我国少数民族传统禁忌的说法中,错误的是( ). [多选题]下列选项中 , 属于表单控件的是 ( ...

  10. linux rm 提示io异常,Hadoop异常 java.io.IOException: Job status not available

    Hadoop集群上跑mapreduce,在job任务执行完成退出时报 java.io.IOException: Job status not available异常.Job client请求job状态 ...

最新文章

  1. 元气满满 开工大吉 2020「升职加薪,走好这三步...」
  2. kafka项目启动_Kafka 探险 源码环境搭建
  3. IT风险的防控水平是一个“木桶”原理
  4. Mysql存储过程中的事务回滚
  5. Discuz论坛架设从零起步之二
  6. 嵌入式开发中,用C++真香!
  7. 搭建简单的SpringBoot开发环境
  8. 家庭记账本开发进度4
  9. Opencv 视频转为图像序列
  10. undefined reference to `major‘
  11. GSM/GPRS MODEM 的上网设置
  12. Redis 命令 - 在线参考
  13. 阿里巴巴开源前端框架--Weex实践
  14. PandoraBox/LEDE SDK交叉编译OpenWrt ipk安装包的方法
  15. css 实现导航菜单
  16. 前端福利!layui可视化布局
  17. Nordic nRF52840实战学习--ble_app_blinky例程
  18. 关于android art模式提取的OAT转dex
  19. 7 款基于 HTML5 Canvas 的超炫 3D 动画效果
  20. Windwos 系统下修改PC的hosts文件,绑定特定的域名和IP地址

热门文章

  1. 软件_迅速增加博客友情链接[博]
  2. 当前主流量化平台整理201705版
  3. 怎么做数据可视化大屏?从设计到上线,一般用这3类工具
  4. WAV音频文件结构及录制
  5. 一个tile布局的下拉框
  6. php memcache技术,Memcache操作类如何在PHP中使用
  7. ad域管理与维护_详解Windows Server 2016如何搭建AD服务器(图文教程)
  8. 创建django项目,8月版本
  9. python命令行进入帮助模式_Python 命令行之旅:深入 click 之选项篇
  10. gdb 命令_gdb实用的调试技巧:启动方式、堆栈信息、单步调试