最基础的读取文件

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException; public class FileIOTest {
public static void main(String[] args) {
File file = new File("E:/abc.txt");
FileInputStream is = null;
try {
is = new FileInputStream(file);
byte[] bytes = new byte[3]; //缓冲容器
int len = -1; //接收长度
while ((len = is.read(bytes)) != -1) {
//字符数组-->字符串,解码
String s = new String(bytes, 0, len);
System.out.println(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
          if(is != null){
            is.clise();
          } } catch (IOException e) {
e.printStackTrace();
}
}
}
}

从文件读取到另一个文件

package com.svs;

import java.io.*;

public class IOTest {
public static void main(String[] args) {
File file = new File("E:/abc.txt");
FileInputStream is = null;
FileOutputStream os = null;
try {
is = new FileInputStream(file);
os = new FileOutputStream("F:/abc.txt");
byte[] bytes = new byte[3];
int len = -1;
while ((len=is.read(bytes)) != -1){
os.write(bytes,0,len);
os.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {//先打开的后关闭
         if(os != null){
  os.close();
         }
         if(is != null){
   is.close();
         }
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

IO流的工具类,抽离出读取、写入、关闭

import java.io.*;

public class FileUtil {
public static void main(String[] args) {
copy("D:/123441.jpg", "E:/123441.jpg");
} /**
* 流的读取与写入
*
* @param srcPath
* @param destPath
*/
public static void copy(String srcPath, String destPath) {
File src = new File(srcPath);
File dest = new File(destPath);
try (InputStream is = new FileInputStream(src);
OutputStream os = new FileOutputStream(dest)) {
byte[] flush = new byte[1024 * 2]; //缓冲容器
int len = -1; //接收长度
while ((len = is.read(flush)) != -1) {
os.write(flush, 0, len);
os.flush(); //刷新缓存
}
} catch (IOException e) {
e.printStackTrace();
}
} }

使用字节数组流读取数据

补充:流的来源或目的地并不一定是文件,也可以是内存中的一块空间,例如一个字节数组。就需使用字节数组流处理,且字节数组流不用关闭。

package com.svs;

import java.io.*;

public class ByteArrayStreamFileUtil {
public static void main(String[] args) {
//使用字节数组流读取,写入数据,字节数组流是不用关闭的
try {
//从硬盘中读取文件,存储到内存中
InputStream is = new FileInputStream("E:/aa.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
copy(is, baos);
//从内存中读取数据,存储到硬盘中
InputStream bais = new ByteArrayInputStream(baos.toByteArray());
OutputStream os = new FileOutputStream("F:/aa.jpg");
copy(bais, os);
closeIO(is, os);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 流的读取与写入
*
* @param is
* @param os
*/
public static void copy(InputStream is, OutputStream os) {
try {
byte[] flush = new byte[1024 * 2]; //缓冲容器
int len = -1; //接收长度
while ((len = is.read(flush)) != -1) {
os.write(flush, 0, len);
os.flush(); //刷新缓存
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* 关闭流
*
* @param is
* @param os
*/
public static void closeIO(InputStream is, OutputStream os) {
try { //先打开的先关闭
if (os != null) {
os.close();
}
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

总结:ByteArrayOutputStream或ByteArrayInputStream是内存读写流,不同于指向硬盘的流,它内部是使用字节数组读内存的,这个字节数组是它的成员变量,当这个数组不再使用变成垃圾的时候,Java的垃圾回收机制会将它回收,所以不需要关流。也就是说,指向内存的流可以不用关闭,指向存储卡/硬盘的流一定要关闭。 

使用字节数组流读取数据-升级版

JDK1.7之后引入

try(    ){
}catch(){
}

方法,省去finally,进行自动关闭。(这是使用 try-with-resources 资源自动释放特性)

package com.svs;

import java.io.*;

public class ByteArrayStreamFileUtil2 {
public static void main(String[] args) {
//JDK1.7之后,引入try(){}方法进行关闭
try (InputStream is = new FileInputStream("E:/aa.jpg");
OutputStream os = new FileOutputStream("F:/aa.jpg");) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
copy(is, baos);
InputStream bais = new ByteArrayInputStream(baos.toByteArray());
copy(bais, os);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 流的读取与写入
*
* @param is
* @param os
*/
public static void copy(InputStream is, OutputStream os) {
try {
byte[] flush = new byte[1024 * 2]; //缓冲容器
int len = -1; //接收长度
while ((len = is.read(flush)) != -1) {
os.write(flush, 0, len);
os.flush(); //刷新缓存
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

字节缓冲流

BufferedInputStream,BufferedOutputStream。字节缓冲流是对读取【性能】的提升,使用字节流时建议加上字节缓冲流。

import java.io.*;

/**
* @Description: 字节缓冲流 BufferedInputStream BufferedOutputStream
* @Description: 字节缓冲流是对读取【性能】的提升,使用字节流时建议加上字节缓冲流
*/ public class BufferedStream {
public static void main(String[] args) {
// long l1= System.currentTimeMillis();
copy("D:/123441.jpg", "E:/123441.jpg");
// long l2= System.currentTimeMillis();
// System.out.println(l2-l1);
} /**
* 流的读取与写入
*
* @param srcPath
* @param destPath
*/
public static void copy(String srcPath, String destPath) {
File src = new File(srcPath);
File dest = new File(destPath);
try (InputStream is = new BufferedInputStream(new FileInputStream(src));
OutputStream os = new BufferedOutputStream(new FileOutputStream(dest))) {
byte[] flush = new byte[1024 * 2]; //缓冲容器
int len = -1; //接收长度
while ((len = is.read(flush)) != -1) {
os.write(flush, 0, len);
os.flush(); //刷新缓存
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

字符缓冲流

import java.io.*;

/**
* @Description: 字符缓冲流 BufferedInputStream BufferedOutputStream
* @Description: 字符缓冲流是对读取【性能】的提升,使用字符流时建议加上字符缓冲流
*/ public class BufferedRWStream {
public static void main(String[] args) {
copy("D:/123441.txt", "E:/123441.txt");
} /**
* 流的读取与写入
*
* @param srcPath
* @param destPath
*/
public static void copy(String srcPath, String destPath) {
File src = new File(srcPath);
File dest = new File(destPath);
try (BufferedReader br = new BufferedReader(new FileReader(src));
BufferedWriter bw = new BufferedWriter(new FileWriter(dest))) {
String line = null;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
bw.flush(); //刷新缓存
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

转换流

InputStreamReader OutputSttreamWriter。
1、以字符流的形式操作字节流(纯文本);2、指定字符集(API手册查看)
import java.io.*;

/**
* @Description: 转换流 InputStreamReader OutputSttreamWriter
* @Description: 1、以字符流的形式操作字节流(纯文本)
* @Description: 2、指定字符集(API手册查看)
*/ public class ConvertTest {
public static void main(String[] args) {
//操作System.in和System.out,均是字节流
try(BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(System.out))){
//循环获取键盘的输入(exit退出),输出此内容
String msg="";
while (!"exit".equals(msg)){
msg=reader.readLine(); //循环读取
writer.write(msg); //循环写出
writer.newLine();
writer.flush(); //强制刷新
}
} catch (IOException e) {
e.printStackTrace();
} }
}

commons-io

Apache下的commonsIO,其中有封装好的FileUtil工具类,实际开发中无需写原生代码,拿来即用即可。

下载链接:http://commons.apache.org/proper/commons-io/download_io.cgi

Java基础IO流 ,文件读取,由易至难的更多相关文章

  1. Java中IO流文件读取、写入和复制

    //构造文件File类 File f=new File(fileName); //判断是否为目录 f.isDirectory(); //获取目录下的文件名 String[] fileName=f.li ...

  2. Java基础-IO流对象之随机访问文件(RandomAccessFile)

    Java基础-IO流对象之随机访问文件(RandomAccessFile) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.RandomAccessFile简介 此类的实例支持对 ...

  3. Java基础IO流(二)字节流小案例

    JAVA基础IO流(一)https://www.cnblogs.com/deepSleeping/p/9693601.html ①读取指定文件内容,按照16进制输出到控制台 其中,Integer.to ...

  4. Java基础-IO流对象之序列化(ObjectOutputStream)与反序列化(ObjectInputStream)

    Java基础-IO流对象之序列化(ObjectOutputStream)与反序列化(ObjectInputStream) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.对象的序 ...

  5. java基础-IO流对象之Properties集合

    java基础-IO流对象之Properties集合 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.Properties集合的特点 Properties类表示了一个持久的属性集. ...

  6. Java基础-IO流对象之字符缓冲流(BufferedWriter与BufferedReader)

    Java基础-IO流对象之字符缓冲流(BufferedWriter与BufferedReader) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.字符缓冲流 字符缓冲流根据流的 ...

  7. Java基础-IO流对象之字节缓冲流(BufferedOutputStream与BufferedInputStream)

    Java基础-IO流对象之字节缓冲流(BufferedOutputStream与BufferedInputStream) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 在我们学习字 ...

  8. Java基础-IO流对象之转换流(InputStreamReader与OutoutStreamWriter)

    Java基础-IO流对象之转换流(InputStreamReader与OutoutStreamWriter) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.转换流概述 我们之前 ...

  9. Java基础-IO流对象之字符类(FileWrite与FileReader)

    Java基础-IO流对象之字符类(FileWrite与FileReader) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.常见编码简介 1>ASCII 我们知道计算机是 ...

  10. Java基础-IO流对象之字节流(Stream)

    Java基础-IO流对象之字节流(Stream) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 在前面我分享的笔记中,我们一直都是在操作文件或者文件夹,并没有给文件中写任何数据.现 ...

随机推荐

  1. Python数据分析与展示第3周学习笔记(北京理工大学 嵩天等)

    入门学习马上结束辽. 1.Pandas库 import pandas as pd 两个数据类型:Series,DataFrame Series类型:数据+索引 自定义索引 b = pd.Series( ...

  2. [LC] 767. Reorganize String

    Given a string S, check if the letters can be rearranged so that two characters that are adjacent to ...

  3. C# 关闭登录窗体,显示主窗体

    首先在programm.cs里设置登录窗体显示 static class Program    {        /// <summary>        /// The main ent ...

  4. string判断是否是正常的ip格式

    废话不多说,上代码 bool isCurrectIP(char *ip) { if (ip == NULL) { return false; } char temp[4]; int count = 0 ...

  5. python学习笔记(13)常用模块列表总结

    os模块: os.remove() 删除文件 os.unlink() 删除文件 os.rename() 重命名文件 os.listdir() 列出指定目录下所有文件 os.chdir() 改变当前工作 ...

  6. Smarty使用-模版中编写js

      在smarty模版中编写js使用literal标签, Literal 标签区域内的数据将被当作文本处理,此时模板将忽略其内部的所有字符信息. 该特性用于显示有可能包含大括号等字符信息的 javas ...

  7. 常用的GIT

    # 初始化相关 git init git add . git commit -m "test001" git remote origin https://github.com/fa ...

  8. 03 - CDH 6.3.x 安装

    CDH 6.3.x 离线安装 环境 CDH 6.3.1 CentOS 7 官方文档 修改主机名,配置host文件 # 根据个人需要修改主机名称 hostnamectl set-hostname nod ...

  9. ISBN|方正|超星|The national academies press|OECD|RSC|Springer Link|Knovel|Encyclopedia Britannica

    图书使用图书分类号ISBN作为图书的ID 大英百科全书(Encyclopedia Britannica)可用于找寻关键词或关键词相关信息,便于构建准确的检索式: Knovel:可使用物理化学性质查找相 ...

  10. python3之urllib基础

    urllib简单应用html=urllib.request.urlopen(域名/网址).read().decode('utf-8')----->--->urlopen-->获取源码 ...