为什么80%的码农都做不了架构师?>>>   

一、多种方式读文件内容

/*java中多种方式读文件
1、按字节读取文件内容
2、按字符读取文件内容
3、按行读取文件内容
4、随机读取文件内容*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;public class ReadFromFile {/*** 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。* * @param fileName*            文件的名*/public static void readFileByBytes(String fileName) {File file = new File(fileName);InputStream in = null;try {System.out.println("以字节为单位读取文件内容,一次读一个字节:");// 一次读一个字节in = new FileInputStream(file);int tempbyte;while ((tempbyte = in.read()) != -1) {System.out.write(tempbyte);}in.close();} catch (IOException e) {e.printStackTrace();return;}try {System.out.println("以字节为单位读取文件内容,一次读多个字节:");// 一次读多个字节byte[] tempbytes = new byte[100];int byteread = 0;in = new FileInputStream(fileName);ReadFromFile.showAvailableBytes(in);// 读入多个字节到字节数组中,byteread为一次读入的字节数while ((byteread = in.read(tempbytes)) != -1) {System.out.write(tempbytes, 0, byteread);}} catch (Exception e1) {e1.printStackTrace();} finally {if (in != null) {try {in.close();} catch (IOException e1) {}}}}/*** 以字符为单位读取文件,常用于读文本,数字等类型的文件* * @param fileName*            文件名*/public static void readFileByChars(String fileName) {File file = new File(fileName);Reader reader = null;try {System.out.println("以字符为单位读取文件内容,一次读一个字节:");// 一次读一个字符reader = new InputStreamReader(new FileInputStream(file));int tempchar;while ((tempchar = reader.read()) != -1) {// 对于windows下,rn这两个字符在一起时,表示一个换行。// 但如果这两个字符分开显示时,会换两次行。// 因此,屏蔽掉r,或者屏蔽n。否则,将会多出很多空行。if (((char) tempchar) != 'r') {System.out.print((char) tempchar);}}reader.close();} catch (Exception e) {e.printStackTrace();}try {System.out.println("以字符为单位读取文件内容,一次读多个字节:");// 一次读多个字符char[] tempchars = new char[30];int charread = 0;reader = new InputStreamReader(new FileInputStream(fileName));// 读入多个字符到字符数组中,charread为一次读取字符数while ((charread = reader.read(tempchars)) != -1) {// 同样屏蔽掉r不显示if ((charread == tempchars.length)&& (tempchars[tempchars.length - 1] != 'r')) {System.out.print(tempchars);} else {for (int i = 0; i < charread; i++) {if (tempchars[i] == 'r') {continue;} else {System.out.print(tempchars[i]);}}}}} catch (Exception e1) {e1.printStackTrace();} finally {if (reader != null) {try {reader.close();} catch (IOException e1) {}}}}/*** 以行为单位读取文件,常用于读面向行的格式化文件* * @param fileName*            文件名*/public static void readFileByLines(String fileName) {File file = new File(fileName);BufferedReader reader = null;try {System.out.println("以行为单位读取文件内容,一次读一整行:");reader = new BufferedReader(new FileReader(file));String tempString = null;int line = 1;// 一次读入一行,直到读入null为文件结束while ((tempString = reader.readLine()) != null) {// 显示行号System.out.println("line " + line + ": " + tempString);line++;}reader.close();} catch (IOException e) {e.printStackTrace();} finally {if (reader != null) {try {reader.close();} catch (IOException e1) {}}}}/*** 随机读取文件内容* * @param fileName*            文件名*/public static void readFileByRandomAccess(String fileName) {RandomAccessFile randomFile = null;try {System.out.println("随机读取一段文件内容:");// 打开一个随机访问文件流,按只读方式randomFile = new RandomAccessFile(fileName, "r");// 文件长度,字节数long fileLength = randomFile.length();// 读文件的起始位置int beginIndex = (fileLength > 4) ? 4 : 0;// 将读文件的开始位置移到beginIndex位置。randomFile.seek(beginIndex);byte[] bytes = new byte[10];int byteread = 0;// 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。// 将一次读取的字节数赋给bytereadwhile ((byteread = randomFile.read(bytes)) != -1) {System.out.write(bytes, 0, byteread);}} catch (IOException e) {e.printStackTrace();} finally {if (randomFile != null) {try {randomFile.close();} catch (IOException e1) {}}}}/*** 显示输入流中还剩的字节数* * @param in*/private static void showAvailableBytes(InputStream in) {try {System.out.println("当前字节输入流中的字节数为:" + in.available());} catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) {String fileName = "C:/temp/newTemp.txt";ReadFromFile.readFileByBytes(fileName);ReadFromFile.readFileByChars(fileName);ReadFromFile.readFileByLines(fileName);ReadFromFile.readFileByRandomAccess(fileName);}
}

二、将内容追加到文件尾部

import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;/*** 将内容追加到文件尾部*/
public class AppendToFile {/*** A方法追加文件:使用RandomAccessFile* * @param fileName*            文件名* @param content*            追加的内容*/public static void appendMethodA(String fileName, String content) {try {// 打开一个随机访问文件流,按读写方式RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");// 文件长度,字节数long fileLength = randomFile.length();// 将写文件指针移到文件尾。randomFile.seek(fileLength);randomFile.writeBytes(content);randomFile.close();} catch (IOException e) {e.printStackTrace();}}/*** B方法追加文件:使用FileWriter* * @param fileName* @param content*/public static void appendMethodB(String fileName, String content) {try {// 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件FileWriter writer = new FileWriter(fileName, true);writer.write(content);writer.close();} catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) {String fileName = "C:/temp/newTemp.txt";String content = "new append!";// 按方法A追加文件AppendToFile.appendMethodA(fileName, content);AppendToFile.appendMethodA(fileName, "append end. n");// 显示文件内容ReadFromFile.readFileByLines(fileName);// 按方法B追加文件AppendToFile.appendMethodB(fileName, content);AppendToFile.appendMethodB(fileName, "append end. n");// 显示文件内容ReadFromFile.readFileByLines(fileName);}
}

转载于:https://my.oschina.net/sati/blog/9538

java 读写文件[多种方法]相关推荐

  1. Java - 读写文件

    Java 读写文件 输入流和输出流的类层次图 FileInputStream 该流用于从文件读取数据. 我们可以使用 new 关键字来创建一个 FileInputStream 对象. FileInpu ...

  2. python的文件读写方法有哪些_python读写文件的方法有哪些

    python读写文件的方法有哪些 发布时间:2020-08-07 11:58:05 来源:亿速云 阅读:87 作者:小新 这篇文章主要介绍python读写文件的方法有哪些,文中介绍的非常详细,具有一定 ...

  3. oracle写java文件_Oracle PL/SQL java读写文件权限问题得到解决

    在ORACLE中PL/SQL利用java读取文件 参考了 的内容,但是出现如下错误: Exception in thread "Root Thread" java.security ...

  4. 八、Python读写文件的方法

    Python读写文件的方法 读取文件的对象:fin = open("data.txt") 写出文件的对象:fout = open("data.txt",&quo ...

  5. java读写文件大全

    使用Java操作文本文件的方法详解 [http://blog.csdn.net/smartcat86/article/details/4085739/] 摘要: 最初java是不支持对文本文件的处理的 ...

  6. java读取文件的方法是_Java读取文件方法大全

    Java读取文件方法大全 2011/11/25 9:18:42  tohsj0806  http://tohsj0806.iteye.com  我要评论(0) 摘要:文章来源:http://www.c ...

  7. Java读写文件的几种方式

    前言 Java中读写文件是非常基本的IO操作了,现在总结一下常见的用法.首先总结一下读取文件的步骤: 根据文件的路径获取到文件File对象 将File对象转换成输入流InputStream 将输入流读 ...

  8. 文件输出 java_用Java读写文件(输入/输出)-教程

    一.文件的Java I/O(输入/输出) 1.1.概述 在现代Java应用程序中,通常使用Java.nio.fileAPI来读写文件. Java将把所有输入作为字节流读取.input stream类是 ...

  9. java读写文件,读超大文件

    一直在处理爬虫,经常能遇到读写文件的操作,很多时候都是读写超大文件,记录如下:一.读文件import java.io.BufferedOutputStream;import java.io.Buffe ...

最新文章

  1. 自定义YUM软件仓库----FTP网络YUM源-----网络YUM源的配置
  2. 单例模式可以分为懒汉式和饿汉式:     懒汉式单例模式:在类加载时不初始化。     饿汉式单例模式:在类加载时就完成了初始化,所以类加载比较慢,但获取对象的速度快。
  3. tensorflow 利用索引获取tensor特定元素
  4. 【机器学习实战】——常见函数积累
  5. 【英语学习】【Level 07】U02 Live Work L2 A place to call my home
  6. My SQL-4 函数
  7. python配置文件封装_Python configparser模块封装及构造配置文件代码示例
  8. Altium Designer 15 PCB图层详解
  9. Python简单数据清洗
  10. 操作系统是介于计算机硬件和用户之间的接口,计算机操作系统知识盘点
  11. 腾讯播放器TCPlayer 报错:The element type must be <video>的解决方法。
  12. linux上传文件到百度云盘(使用shell脚本,不依赖python库)
  13. Software Testing - Browser Driver在Selenium中的作用是什么
  14. 滴滴共享单车在深圳被叫停;六六接受京东道歉;宝马发布最新充电网络计划丨价值早报
  15. 绘制几何图形,生成辅助线的思路
  16. C++描述 104.仓库选址
  17. 解决Rem的适配问题
  18. Windows+Anaconda+tensorflow+keras深度学习框架搭建--reproduced
  19. 微信页面触发返回按钮回到聊天界面
  20. 【归并排序】基础代码

热门文章

  1. 不懂AI的我,是如何搞开发的?
  2. 一文看尽CVPR 2019十大新研究:“不看也知”成热点,无人车新增重磅开源数据集...
  3. StringUtils工具类的isBlank()方法使用说明
  4. JS 中 this 的指向
  5. php查询mysql并缓存到redis
  6. Kotlin教程(九)泛型
  7. thinkphp-查询数据-基本查询
  8. w3m - 命令行下的浏览器
  9. 基于HTML5实现3D热图Heatmap应用
  10. USACO1.1 Broken Necklace (beads)