/*Java 输入流(读取txt文件)*/

时间:2023-02-24 20:55:43

读取txt文件有两种方式,第一种是字符型读取,第二种是字节型读取。
字节流(Byte Stream)每次读写8位二进制数,
也称为二进制字节流或位流。
字符流一次读写16位二进制数,并将其做一个字符而不是二进制位来处理。需要注意的是,为满足字符的国际化表示,Java语言的字符编码
采用的是16位的Unicode码,而普通文本文件中采用的是8位ASCⅡ码。

一.字符型读取
package cn.newdream.class68.chapter04;
import java.io.FileReader;
import java.io.IOException;
public class CharReader_02 {
public static void main(String[] args) throws IOException {
/**
* 创建读取字符数据的流对象。
* 读取路径不正确时会抛 IOException
* 用一个读取流对象关联一个已存在文件。
*/

String path =System.getProperty("user.dir")+"\\data\\test.txt";
FileReader fr = new FileReader(path);
/**
* 用Reader中的read方法读取字符。
*/

/*String ah = fr.read();
System.out.print((char)String ah);
String ch1 = fr.read();
System.out.print((char)ch1);
String ch2 = fr.read();
System.out.print((char)ch2);*/

int ch = 0;
while((ch = fr.read()) != -1){
System.out.print((char)ch);
}
fr.close();
}
}
//FileReader类
1,构造方法
FileReader fr = new FileReader(String fileName);//使用带有指定文件的String参数的构造方法。创建该输入流对象。并关联源文件。
2,主要方法
int read(); // 读取单个字符。返回作为整数读取的字符,如果已达到流末尾,则返回 -1。
int read(char []cbuf);//将字符读入数组。返回读取的字符数。如果已经到达尾部,则返回-1。
void close();//关闭此流对象。释放与之关联的所有资源。

二.字节型读取

package cn.newdream.class68.chapter04;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class ByteReader_02 {
public static void main(String[] args) throws Exception {
String filePath = System.getProperty("user.dir");
filePath = filePath + "\\data\\hello.txt";
FileInputStream in = new FileInputStream(filePath);
//System.out.println((char)in.read()); //一个字符读取
int tempbyte;
while ((tempbyte = in.read()) != -1) {
//System.out.write(tempbyte);
//System.out.println((char)tempbyte);
System.out.print((char)tempbyte);
}
in.close();
}

}