`
yxwang0615
  • 浏览: 559775 次
  • 性别: Icon_minigender_1
  • 来自: 青岛
社区版块
存档分类
最新评论

java i/o 流

    博客分类:
  • java
阅读更多

一、理解java的I/O流:

java io包中 大体分两种流,1.字节流  2.字符流
在从功能分,有输入流(写出流),输出流(写入流)。

输入流就是从文件或者其他的介质中读取内容。(硬盘 → 内存,输入到内存,参照物是内存)

又称写出流(写出到硬盘,参照物是硬盘)。


输出流,就是从流中向文件或者其他介质写入内容。(内存 → 硬盘等,输出到内存)

又称写入流(写入到硬盘)

 

由上可见数据流的命名和流向是按照不同的参照物来划分的。

 

 二、字节流和字符流:

字节流操作的数据单元是字节,字符流操作的数据单元是字符。

 

1.inputStream 和 Reader是所有输入流的基类。

InputStream包含三个方法:

 

① int read():从输入流中读取单个字节;返回-1表示到了输入流的结束点。

public abstract int read()
                  throws IOException
Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

A subclass must provide an implementation of this method.

 

Returns:
the next byte of data, or -1 if the end of the stream is reached.
Throws:
IOException - if an I/O error occurs.

 

 

②从输入流中读取最多len字节的数据,并将其存储在数组b中,放入b数组时,并不是从数组起点开始,而是从off位置开始,返回实际读取的字节数。返回-1表示到了输入流的结束点。

public int read(byte[] b,
                int off,
                int len)
         throws IOException
Reads up to len bytes of data from the input stream into an array of bytes. An attempt is made to read as many as len bytes, but a smaller number may be read. The number of bytes actually read is returned as an integer.

This method blocks until input data is available, end of file is detected, or an exception is thrown.

If b is null, a NullPointerException is thrown.

If off is negative, or len is negative, or off+len is greater than the length of the array b, then an IndexOutOfBoundsException is thrown.

If len is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; otherwise, at least one byte is read and stored into b.

The first byte read is stored into element b[off], the next one into b[off+1], and so on. The number of bytes read is, at most, equal to len. Let k be the number of bytes actually read; these bytes will be stored in elements b[off] through b[off+k-1], leaving elements b[off+k] through b[off+len-1] unaffected.

In every case, elements b[0] through b[off] and elements b[off+len] through b[b.length-1] are unaffected.

If the first byte cannot be read for any reason other than end of file, then an IOException is thrown. In particular, an IOException is thrown if the input stream has been closed.

The read(b, off, len) method for class InputStream simply calls the method read() repeatedly. If the first such call results in an IOException, that exception is returned from the call to the read(b, off, len) method. If any subsequent call to read() results in a IOException, the exception is caught and treated as if it were end of file; the bytes read up to that point are stored into b and the number of bytes read before the exception occurred is returned. Subclasses are encouraged to provide a more efficient implementation of this method.

 

Parameters:
b - the buffer into which the data is read.
off - the start offset in array b at which the data is written.
len - the maximum number of bytes to read.
Returns:
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.
Throws:
IOException - if an I/O error occurs.
NullPointerException - if b is null.

③从输入流中读取最多b.length个字节的数据,并将其存储在b中,返回实际读取的字节数。返回-1即到了输入流的结束点

public int read(byte[] b)
         throws IOException
Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown.

If b is null, a NullPointerException is thrown. If the length of b is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; otherwise, at least one byte is read and stored into b.

The first byte read is stored into element b[0], the next one into b[1], and so on. The number of bytes read is, at most, equal to the length of b. Let k be the number of bytes actually read; these bytes will be stored in elements b[0] through b[k-1], leaving elements b[k] through b[b.length-1] unaffected.

If the first byte cannot be read for any reason other than end of file, then an IOException is thrown. In particular, an IOException is thrown if the input stream has been closed.

The read(b) method for class InputStream has the same effect as:

 read(b, 0, b.length) 

 

Parameters:
b - the buffer into which the data is read.
Returns:
the total number of bytes read into the buffer, or -1 is there is no more data because the end of the stream has been reached.
Throws:
IOException - if an I/O error occurs.
NullPointerException - if b is null.

InputStream 和 Reader 都是抽象类,本身不能创建实例,

他们分别有一个用于读取文件的输入流,FileInputStream 和FileReader 。

 

FileInputStream示例:

public class FileInputStreamTest {
	public static void main(String[] args) throws IOException {
		FileInputStream fis = new FileInputStream("e:\\test.sql");
		//创建一个长度为1024的容器
		byte[] bbuf = new byte[1024];
		//用于保存容器中存储字节数实际长度
		int hasRead = 0;
		
		while((hasRead = fis.read(bbuf))>0){//每次循环都重新给hasRead赋值
			//将字节数组转换成字符串输入
			System.out.println(new String(bbuf,0,hasRead));
		}
		fis.close();
	}
}

 上例创建了一个长度1024的字节数组来读取该文件,实际上该文件的长度还不到1024字节,也就是说程序只需要执行一次循环即可读取全部内容,如果创建较小的字节数组,程序在输出中文时可能会初选乱码,引文文件保存的时候才用gbk的编码方式,每个中文字符占2个字节,如果字节数组将一个中文字符拆分进了2个数组,将会出现乱码。

 

FileReader示例:

public class FileReadTest {
	
	public static void main(String[] args) throws IOException {
		FileReader fr = null;
		try {
			fr = new FileReader("e:/test.sql");
			//创建一个长度为32位的"容器"
			char[] cbuf = new char[32];
			//容器中字符的位数
			int hasRead = 0;
			
			while((hasRead = fr.read(cbuf)) > 0){
				System.out.println(new String(cbuf,0,hasRead));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			fr.close();
		}
	}
}

 

 

Reader包含三个方法:

① int read():从输入流中读取单个字节;读不到返回-1

public int read()
         throws IOException
Read a single character.

 

Overrides:
read in class Reader
Returns:
The character read, or -1 if the end of the stream has been reached
Throws:
IOException - If an I/O error occurs

② 从输入流中读取最多

public int read(char[] b)
         throws IOException
Read a single character.

 

Overrides:
read in class Reader
Returns:
The character read, or -1 if the end of the stream has been reached
Throws:
IOException - If an I/O error occurs

public int read(char[] cbuf,
                int offset,
                int length)
         throws IOException
Read characters into a portion of an array.

 

Specified by:
read in class Reader
Parameters:
cbuf - Destination buffer
offset - Offset at which to start storing characters
length - Maximum number of characters to read
Returns:
The number of characters read, or -1 if the end of the stream has been reached
Throws:
IOException - If an I/O error occurs

 2.outputstream 和 Writer 输出流 。

两个输出流都提供了如下三个方法:

① void write(int c) 将指定的字节/字符输出到输出流中,c可代表字节、字符

② void write(byte[]/char[] buf)

叁 void write(byte[]/char[] buf, int off ,int len):将字节数组、字符数组中从off位置开始长度为len 的字符输出到指

定输出流中。

 

FileOutputStream示例:

public class FileOutputStreamTest {
	public static void main(String[] args) throws IOException {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try{
			fis = new FileInputStream("e:\\test.sql");
			fos = new FileOutputStream("test1.sql");
			//创建一个长度为32byte的容器
			byte[] bbuf = new byte[32];
			//用于保存下面read方法的返回值
			int hasRead = 0;
			
			while((hasRead = fis.read(bbuf))>0){//每次循环都重新给hasRead赋值,0表示读完
				fos.write(bbuf);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}	
		finally{
			if(fis != null){
				fis.close();
			}
			if(fos != null){
				fos.close();
			}
		}
	}
}

 FileWriter 示例:

public class FileWriterTest{
	public static void main(String[] args) throws IOException {
		FileWriter  fw = null;
		try {
			fw = new FileWriter("song.txt");
			fw.write("我们的家乡,\r\n");
			fw.write("在希望的田野上。\r\n");
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			fw.close();
		}
	}
}

 

分享到:
评论

相关推荐

    Java I/O流通讯录

    Java I/O流通讯录是一个基于Java编程语言设计的实用程序,它主要用于演示和学习Java的I/O流操作。在这个项目中,开发者通过I/O流实现了对文件的读写功能,从而构建了一个简单的通讯录系统。这个系统允许用户进行添加...

    Java I/O 流代码实例大全(01~09)

    Java I/O 流代码实例大全(01~09) File、FileInputStream、FileOutputStream、FileReader、FileWriter、BufferedInputStream、BufferedOutputStream、BufferedReader、BufferedWriter

    java基础之I/O流

    Java中的I/O流是程序与外部数据交互的重要机制,它允许数据在程序、文件、网络等之间流动。I/O流分为两大类:字符流(Character Stream)和字节流(Byte Stream),每类又分为输入流(Input Stream)和输出流...

    java i/o流读取写入字符流

    读取写入文件,javai/o流字符流 eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee

    java I/O流总结

    这是一篇关于javaSe的基础班关于IO流的全套总结,希望能对你的基础学习有所帮助。

    Java I/O 流代码实例大全(01~15)

    Java I/O 流代码实例大全(01~15) File、FileInputStream、FileOutputStream、FileReader、FileWriter、BufferedInputStream、BufferedOutputStream、BufferedReader、BufferedWriter、ByteArrayInputStream、...

    java对I/O流的处理

    Java中的I/O流处理是程序与外部设备交互数据的关键机制,包括从文件、网络、内存等数据源读取数据和向这些目标写入数据。I/O流系统在Java的`java.io`包中被实现,提供了丰富的类和接口来支持各种类型的流操作。 **I...

    Java I/O, 2nd Edition

    1. **Java I/O基础**:书中首先介绍了Java I/O的基本概念,如流、缓冲区、字符编码和文件操作。流是数据传输的核心机制,分为字节流和字符流两大类,包括输入流和输出流。缓冲区则可以提高I/O操作的效率,减少磁盘和...

    Java I/O 过滤流-带格式的读写操作

    过滤流(Filter Stream)是Java I/O框架中的一个重要概念,它提供了一种优雅的方式来进行数据的读写操作,同时允许我们添加额外的功能,如字符编码转换、数据压缩等。本篇文章将深入探讨Java I/O中的过滤流,以及...

    Java 新I/O

    Java 新I/O,也称为NIO(New Input/Output),是Java平台中对传统I/O模型的一种改进。在Java 1.4版本中引入的NIO库为开发人员提供了更高效、非阻塞的数据处理方式,特别适用于高并发、低延迟的系统。NIO的核心在于...

    java数据流 I/O系统

    在Java中,I/O操作是通过数据流的概念来实现的。 数据流的基本概念涉及数据的流动方向和组织层次。数据流可以分为输入数据流和输出数据流,前者只能读取数据,后者只能写入数据。在Java中,`java.io`包提供了这些...

    Java I/O编程 java

    在Java I/O编程中,理解不同类型的流及其用途至关重要。字节流和字符流分别处理二进制和文本数据,过滤流提供了额外的功能,管道流实现了线程间的通信,对象流使得对象可以持久化。掌握这些基础,开发者能够有效地...

    Java I/O, NIO and NIO.2

    Java I/O 包含了用于读写文件、网络通信、字符流和字节流的各种类,如InputStream、OutputStream、Reader、Writer以及它们的子类。例如,FileInputStream和FileOutputStream用于文件操作,SocketInputStream和...

    Javaio流思维导图

    在这个思维导图中,我们将深入探讨Java I/O流的各个方面。 首先,Java I/O流分为两大类:字符流和字节流。字符流处理的是Unicode字符,如Java中的char类型,而字节流则处理单个字节的数据。字节流包括InputStream和...

    java I/O类的使用

    Java 1.0 和 1.1 中的I/O类主要是基于两个基础类:`InputStream`和`OutputStream`,它们处理字节流。`InputStream`家族包括了如`ByteArrayInputStream`、`FileInputStream`等,它们分别从字节数组或文件中读取数据。...

    Java I/O总结

    1. **流的层次结构**:Java I/O流按照功能的不同分为基本流和高级流。基本流如`FileInputStream`、`FileOutputStream`等,主要用于直接与设备交互;高级流如`BufferedReader`、`PrintWriter`等,则是在基本流的基础...

    JAVA文件I/O流上传类

    JAVA文件I/O流上传类 MyFileSeparate 文件上传

    深入分析 Java I/O 的工作机制(转载)

    Java I/O(输入/输出)系统是Java编程语言中用于处理数据流的重要组成部分,它允许程序与外部资源如文件、网络、硬件设备等进行交互。深入理解Java I/O的工作机制对于开发高效、可靠的系统至关重要。以下是对Java I/...

    Java I/O 第二版

    OReilly.Java.I.O.2nd.Edition.May.2006 Java的io包主要包括: 1. 两种流:字节流(byte Stream)和字符流(character stream),这两种流不存在所谓的谁代替谁、谁比谁高级之说,它们互为补充,只是侧重点不同...

    Java课程设计报告书-学生版-1_I/O流与文件课程设计_

    在Java编程语言中,I/O流(Input/Output Stream)是处理数据输入和输出的核心机制。本课程设计报告书——“Java课程设计报告书-学生版-1_I/O流与文件课程设计_”旨在帮助学生深入理解并掌握如何在Java中进行文件操作...

Global site tag (gtag.js) - Google Analytics