IO代码记忆
FileWriter fw = new FileWriter("hello.txt"); String s = "hello world"; fw.write(s,0,s.length()); fw.flush(); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("hello2.txt")); osw.write(s,0,s.length()); osw.flush(); PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("hello3.txt")),true); pw.println(s);
FileWriter fw = new FileWriter("hello.txt"); String s = "hello world"; fw.write(s,0,s.length()); fw.flush(); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("hello2.txt")); osw.write(s,0,s.length()); osw.flush(); PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("hello3.txt")),true); pw.println(s);
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个字节,则读剩下的字节。 //将一次读取的字节数赋给byteread while ((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); } }
IO代码记忆的更多相关文章
- IO—代码—基础及其用例
字节流:文件.图片.歌曲 使用字节流的应用场景:如果是读写的数据都不需要转换成字符的时候,则使用字节流. 字节流处理单元为1个字节, 操作字节和字节数组.不能直接处理Unicode字符 字节流可用于任 ...
- Java Socket, DatagramSocket, ServerSocketChannel io代码跟踪
Java Socket, DatagramSocket, ServerSocketChannel这三个分别对应了,TCP, udp, NIO通信API封装.JDK封装了,想跟下代码,看下具体最后是怎么 ...
- 为了记忆和方便翻阅 vue构建后的结构目录说明
一. ├── build // 项目构建(webpack)相关代码 记忆:(够贱) 9个 │ ├── build.js // 生产环 ...
- socket.io简单入门(一.实现简单的图表推送)
引子:随着nodejs蓬勃发展,虽然主要业务系统因为架构健壮性不会选择nodejs座位应用服务器.但是大量的内部系统却可以使用nodejs试水,大量的前端开发人员转入全堆开发也是一个因素. 研究本例主 ...
- socket.io稳定性及事件测试
socket.io测试报告 1.socekt.io能坚持多久 将服务器上的socekt.io代码从早上9:30分开始运行到晚上18点,每100毫秒发送一条数据,数据大概15个字符,同时开启5个连接 结 ...
- 并发式IO的解决方案:多路非阻塞式IO、多路复用、异步IO
在Linux应用编程中的并发式IO的三种解决方案是: (1) 多路非阻塞式IO (2) 多路复用 (3) 异步IO 以下代码将以操作鼠标和键盘为实例来演示. 1. 多路非阻塞式IO 多路非阻塞式IO访 ...
- Koa,React和socket.io
安装 socket.io/socket.io-client 基本用法 首先koa和socket.io代码片段 const server = require('http'). const server ...
- python学习之路-第八天-文件IO、储存器模块
文件IO.储存器模块 文件IO 代码示例: # -*- coding:utf-8 -*- #! /usr/bin/python # filename:using_file.py poem = '''\ ...
- File IO(NIO.2):路径类 和 路径操作
路径类 Java SE 7版本中引入的Path类是java.nio.file包的主要入口点之一.如果您的应用程序使用文件I / O,您将需要了解此类的强大功能. 版本注意:如果您有使用java.io. ...
随机推荐
- 安装spark单机环境
(假定已经装好的hadoop,不管你装没装好,反正我是装好了) 1 下载spark安装包 http://spark.apache.org/downloads.html 下载spark-1.6.1-bi ...
- .net 框架
目录 API 应用框架(Application Frameworks) 应用模板(Application Templates) 人工智能(Artificial Intelligence) 程序集处理( ...
- Java---hashCode()和equals()
1.hashCode()和equals() API hashCode()和equals()都来自上帝类Object, 所有的类都会拥有这两个方法,特定时,复写它们. 它们是用来在同一类中做比较用的,尤 ...
- jQuery 数据操作函数(九)
.clearQueue() 从队列中删除所有未运行的项目. .data() 存储与匹配元素相关的任意数据. jQuery.data() 存储与指定元素相关的任意数据. .dequeue() 从队列最前 ...
- 基于vue2+vuex+vue-router+sass+webpack的网易云音乐
[本博客为原创:http://www.cnblogs.com/HeavenBin/] 前言: 这段时间写的一个项目,供给大家互相学习,有什么疑问可以issues我. 源码地址:https://git ...
- linux 实时同步inotify
#实时同步inotify 1.inotify简介inotify是一种强大的,细腻度的,异步的文件系统事件监控机制,linux内核从2.6.13起,加入了inotify支持,通过INOTIFY可以监控文 ...
- asp.net mvc 记录Action耗时
可能有些时候需要记录Action的执行时间来优化系统功能,这时可以用过滤器来实现. 新建项目 项目名称随便取 身份验证:不进行身份验证 安装Nlog 这里使用NLog来输出日志,具体使用说明请看:ht ...
- Global exception handling in asp.net core webapi
在.NET Core中MVC和WebAPI已经组合在一起,都继承了Controller,但是在处理错误时,就很不一样,MVC返回错误页面给浏览器,WebAPI返回Json或XML,而不是HTML.Us ...
- python 组合样例
class Bill(): def __init__(self, description): self.description = description class Tail(): def __in ...
- [译]Python面试中8个必考问题
1.下面这段代码的输出结果是什么?请解释. def extendList(val, list=[]): list.append(val) return list list1 = extendList( ...