java学习:文件读写
2012-11-03 21:24
393 查看
java中有好几种读写文件的方法,但是个人觉得最简单的还是FileInputStream、FileOutputStream类,示例代码:
调用示例:
package jmyang.file; import java.io.*; public class FileTest { /* * 删除文件 */ public static boolean delete(String fileName){ boolean result = false; File f = new File(fileName); if (f.exists()){ try{ result = f.delete(); } catch(Exception e){ e.printStackTrace(); } } else{ result = true; } return result; } /* * 读取文件 */ public static String read(String fileName) { File f = new File(fileName); if (!f.exists()) { return "File not found!"; } FileInputStream fs; String result = null; try { fs = new FileInputStream(f); byte[] b = new byte[fs.available()]; fs.read(b); fs.close(); result = new String(b); } catch (Exception e) { e.printStackTrace(); } return result; } /* *写文件 */ public static boolean write(String fileName, String fileContent) { boolean result = false; File f = new File(fileName); try { FileOutputStream fs = new FileOutputStream(f); byte[] b = fileContent.getBytes(); fs.write(b); fs.flush(); fs.close(); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /* * 追加内容到文件 */ public static boolean append(String fileName, String fileContent) { boolean result = false; File f = new File(fileName); try { if (f.exists()) { FileInputStream fsIn = new FileInputStream(f); byte[] bIn = new byte[fsIn.available()]; fsIn.read(bIn); String oldFileContent = new String(bIn); //System.out.println("旧内容:" + oldFileContent); fsIn.close(); if (!oldFileContent.equalsIgnoreCase("")) { fileContent = oldFileContent + "\r\n" + fileContent; //System.out.println("新内容:" + fileContent); } } FileOutputStream fs = new FileOutputStream(f); byte[] b = fileContent.getBytes(); fs.write(b); fs.flush(); fs.close(); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } }
调用示例:
//FileTest f = new FileTest(); //System.out.println(f.read("c:/a.txt")); final String fileName = "c:/a.txt"; System.out.println(FileTest.delete(fileName)); //System.out.println(FileTest.append(fileName,"这是java写入的内容1")); //System.out.println(FileTest.append(fileName,"这是java写入的内容2"));
相关文章推荐
- 【Java学习20170413】Excel文件读写
- 【安卓学习笔记】JAVA基础-字符流及打文件的读写
- Java学习笔记——File类文件管理及IO读写、复制操作
- Android:java byte数组文件读写学习实例
- JAVA学习提高之----Java的多种方式读写Properties文件
- Java学习笔记——File类文件管理及IO读写、复制操作
- 【java学习笔记】文件读写(IO流)
- JAVA学习第四十七课 — IO流(一):文件的读写
- JAVA基础学习之流的简述及演示案例、用缓冲区方法buffer读写文件、File类对象的使用、Serializable标记接口(6)
- java学习[0]_文件读写
- json学习六——>Java 读写json格式的文件方法详解
- iMOOC学习笔记:Java的Excel读写操作入门实践-利用POI解析Excel文件(二)
- java学习第50天,文件读写
- JAVA学习第四十七课 — IO流(一):文件的读写
- Java I/O学习 文件读写工具
- [学习笔记]Java 中对文件的读写操作之比较
- Thinking In Java学习笔记之文件读写实用工具
- JAVA学习提高之----JAVA读写Properties文件
- Java学习笔记---实现文件随机读写-RandomAccessFile