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代码记忆的更多相关文章

  1. IO—代码—基础及其用例

    字节流:文件.图片.歌曲 使用字节流的应用场景:如果是读写的数据都不需要转换成字符的时候,则使用字节流. 字节流处理单元为1个字节, 操作字节和字节数组.不能直接处理Unicode字符 字节流可用于任 ...

  2. Java Socket, DatagramSocket, ServerSocketChannel io代码跟踪

    Java Socket, DatagramSocket, ServerSocketChannel这三个分别对应了,TCP, udp, NIO通信API封装.JDK封装了,想跟下代码,看下具体最后是怎么 ...

  3. 为了记忆和方便翻阅 vue构建后的结构目录说明

    一. ├── build              // 项目构建(webpack)相关代码             记忆:(够贱)    9个 │ ├── build.js       // 生产环 ...

  4. socket.io简单入门(一.实现简单的图表推送)

    引子:随着nodejs蓬勃发展,虽然主要业务系统因为架构健壮性不会选择nodejs座位应用服务器.但是大量的内部系统却可以使用nodejs试水,大量的前端开发人员转入全堆开发也是一个因素. 研究本例主 ...

  5. socket.io稳定性及事件测试

    socket.io测试报告 1.socekt.io能坚持多久 将服务器上的socekt.io代码从早上9:30分开始运行到晚上18点,每100毫秒发送一条数据,数据大概15个字符,同时开启5个连接 结 ...

  6. 并发式IO的解决方案:多路非阻塞式IO、多路复用、异步IO

    在Linux应用编程中的并发式IO的三种解决方案是: (1) 多路非阻塞式IO (2) 多路复用 (3) 异步IO 以下代码将以操作鼠标和键盘为实例来演示. 1. 多路非阻塞式IO 多路非阻塞式IO访 ...

  7. Koa,React和socket.io

    安装  socket.io/socket.io-client 基本用法 首先koa和socket.io代码片段 const server = require('http'). const server ...

  8. python学习之路-第八天-文件IO、储存器模块

    文件IO.储存器模块 文件IO 代码示例: # -*- coding:utf-8 -*- #! /usr/bin/python # filename:using_file.py poem = '''\ ...

  9. File IO(NIO.2):路径类 和 路径操作

    路径类 Java SE 7版本中引入的Path类是java.nio.file包的主要入口点之一.如果您的应用程序使用文件I / O,您将需要了解此类的强大功能. 版本注意:如果您有使用java.io. ...

随机推荐

  1. RSA,DES,RC4,3DES ,MD5

    一,RSA算法基于一个十分简单的数论事实:将两个大质数相乘十分容易,但是想要对其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥. RSA算法是一种非对称密码算法,所谓非对称,就是指该算法需 ...

  2. 豹哥嵌入式讲堂:ARM开发之文件详解(2)- linker文件

    大家好,我是豹哥,猎豹的豹,犀利哥的哥.今天豹哥给大家讲的是嵌入式开发里的linker文件. 在前一节课source文件详解里,豹哥给大家系统地介绍了source文件,source文件是嵌入式工程里典 ...

  3. ExpandableListView的完美实现,JSON数据源,右边自定义图片

    转载请标明出处: http://www.cnblogs.com/dingxiansen/p/8194669.html 本文出自:丁先森-博客园 最近在项目中要使用ExpandableListView来 ...

  4. 01-Java基础及面向对象

    JAVA基础知识 Java 是SUN(Stanford University Network,斯坦福大学网络公司)1995年推出的一门面向 Internet 的高级编程语言. Java 虚拟机(JVM ...

  5. 执行查询“BACKUP LOG [XXX] TO DISK = N'F:\\BackData\\事务日至备份\\...”失败,错误如下:“无法执行 BACKUP LOG,因为当前没有数据库备份。 BACKUP LOG 正在异常终止。

    执行查询"BACKUP LOG [XXX] TO  DISK = N'F:\\BackData\\事务日至备份\\..."失败,错误如下:"无法执行 BACKUP LOG ...

  6. SQL语言的分类

    本文转自https://www.cnblogs.com/fjfzhkb/archive/2007/10/18/929108.html SQL语言共分为四大类:数据查询语言DQL,数据操纵语言DML, ...

  7. TPYBoard读取芯片上的温度传感器

    转载请以链接形式注明文章来源,公众号:MicroPython玩家汇 一.STM32内部温度传感器概要 STM32芯片内部一项独特的功能就是内部集成了一个温度传感器,因为是内置,所以测试的是芯片内部的温 ...

  8. label按钮和文字对齐

    label按钮和文字对齐 做表单的时候,经常遇到:复选框和文字对不齐的情况 ========================== 下面方法可以对齐 <!--label [[--> < ...

  9. jdk8新特性(文章推荐)

    文章推荐 jdk9都已经出来了,虽然很多项目都已经使用jdk8,但是很少会用到jdk8中的新特性.本人经常用的到也就是使用Stream,Lambda,但也仅仅是使用,基本不知道什么Function,C ...

  10. PHP连接LDAP进行登录验证

    基于安全性考虑,准备把PHP做的自动化平台加入ldap登录验证,具体做法如下: 了解背景: LDAP 的全称是"轻量级目录访问协议(Lightweight Directory Access ...