导航:首页 > 编程语言 > java字符流读取

java字符流读取

发布时间:2022-10-20 21:44:24

java中怎样将文件的内容读取成字符串

java中有四种将文件的内容读取成字符串

方式一:

Java code

/**

*以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。

*当然也是可以读字符串的。

*/

/*貌似是说网络环境中比较复杂,每次传过来的字符是定长的,用这种方式?*/

publicStringreadString1()

{

try

{

//FileInputStream用于读取诸如图像数据之类的原始字节流。要读取字符流,请考虑使用FileReader。

FileInputStreaminStream=this.openFileInput(FILE_NAME);

ByteArrayOutputStreambos=newByteArrayOutputStream();

byte[]buffer=newbyte[1024];

intlength=-1;

while((length=inStream.read(buffer)!=-1)

{

bos.write(buffer,0,length);

//.write方法SDK的解释是m.

//当流关闭以后内容依然存在

}

bos.close();

inStream.close();

returnbos.toString();

//为什么不一次性把buffer得大小取出来呢?为什么还要写入到bos中呢?returnnew(buffer,"UTF-8")不更好么?

//returnnewString(bos.toByteArray(),"UTF-8");

}

}

方式二:

Java code

方式四:

Java code

/*InputStreamReader+BufferedReader读取字符串,InputStreamReader类是从字节流到字符流的桥梁*/

/*按行读对于要处理的格式化数据是一种读取的好方式*/

()

{

intlen=0;

StringBufferstr=newStringBuffer("");

Filefile=newFile(FILE_IN);

try{

FileInputStreamis=newFileInputStream(file);

InputStreamReaderisr=newInputStreamReader(is);

BufferedReaderin=newBufferedReader(isr);

Stringline=null;

while((line=in.readLine())!=null)

{

if(len!=0)//处理换行符的问题

{

str.append(" "+line);

}

else

{

str.append(line);

}

len++;

}

in.close();

is.close();

}catch(IOExceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}

returnstr.toString();

}

② java分别以字节流和字符流的两种方式读取文件内容


importjava.io.BufferedReader;

importjava.io.File;

importjava.io.FileInputStream;

importjava.io.IOException;

importjava.io.InputStreamReader;

importjava.io.PrintWriter;

publicclassTest10{

/**

*复制当前的源程序到项目的根目录

*@throwsIOException

*/

publicstaticvoidmain(String[]args)throwsIOException{

/*

*1:读取原文件

*2:项目标文件中写

*3:使用缓冲流按行读写

*/

FileInputStreamfis=newFileInputStream("src"+File.separator+"day01"+File.separator+"Test1.java");


//转化为字符输出流

InputStreamReaderisr=newInputStreamReader(fis);


//按行为单位读取字符串

BufferedReaderbr=newBufferedReader(isr);


//

PrintWriterpw=newPrintWriter("Test1.java");


Stringline=null;

while((line=br.readLine())!=null){

pw.println(line);

}

pw.close();

br.close();

}

}

③ JAVA字符流方式读取文件 问题!

public class ReadFromFile {
/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
*/
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) {
}
}
}
}

/**
* 以字符为单位读取文件,常用于读文本,数字等类型的文件
*/
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下,\r\n这两个字符在一起时,表示一个换行。
// 但如果这两个字符分开显示时,会换两次行。
// 因此,屏蔽掉\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) {
}
}
}
}

/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
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) {
}
}
}
}

/**
* 随机读取文件内容
*/
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) {
}
}
}
}

/**
* 显示输入流中还剩的字节数
*/
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);
}
}

复制代码

5、将内容追加到文件尾部

public class AppendToFile {
/**
* A方法追加文件:使用RandomAccessFile
*/
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
*/
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);
}
}

④ Java字符流和字节流对文件操作的区别

Java字符流是处理字符(Char)对象用的,字节流是处理字节(Byte)对象用的。处理的目标对象不同,处理方法也就不一样了。
字符流处理的基本单位是字符(Java中的字符是16位的),输入流以Reader为基础,输出流以Writer为基础;
字节流的基本单位是字节(Java中的字节是8位的),输入流以
InputStream为基础,输出流以
OutputStream为基础;
字符流在输入时可以按字符读取,也可以按行读取,会去掉回车换行,常用于读取字符数据;
而字节流按字节读取,不作任何处理,常用于读取二进制数据。
Java中的字符在内部都是使用Unicode进行表示的,因此,要正确读取字符数据,需要知道字符的编码字符集,字符流提供编码字符集的指定,如果不指定使用系统默认的方式对字符数据进行编码转换,这个编码字符集不正确,会造成读进来的地字符出现乱码。
字节流虽然是读取二进制数据用的,但也可以读取字符文件,按字节进行处理,读进来之后可以根据编码字符集进行转换,也可以变成字符串。

⑤ java 中 字符流是否可以读取字节流写的 txt文件

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下,\r\n这两个字符在一起时,表示一个换行。
// 但如果这两个字符分开显示时,会换两次行。
// 因此,屏蔽掉\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]);
}
}
}
}

⑥ java中字节流读写和字符流读写哪个效率更高

Java流在处理上分为字符流和字节流。字符流处理的单元为2个字节的Unicode字符,分别操作字符、字符数组或字符串,而字节流处理单元为1个字节,操作字节和字节数组。Java内用Unicode编码存储字符,字符流处理类负责将外部的其他编码的

⑦ java用字符流读写文件

代码已写好,希望对你有帮助,顺便求好评。

packagearchitecture;

importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.FileReader;
importjava.io.FileWriter;
importjava.io.IOException;

/**
*
*@authorWangZhenhui
*@blogwww.soaringroad.com
*
*/
{

/**
*main
*@paramargs
*/
publicstaticvoidmain(String[]args){
StringfilePath="d:\out2.txt";
write(filePath);
read(filePath);
}

/**
*Read
*@paramfilePathfilepath
*/
publicstaticvoidread(StringfilePath){
FileReaderfr=null;
StringBuilderresult=newStringBuilder();
;
try{
fr=newFileReader(newFile(filePath));
char[]charArray=newchar[1024];
while(fr.read(charArray)!=-1){
result.append(charArray);
}
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
if(fr!=null){
try{
fr.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
System.out.println(result.toString());
}


/**
*Write
*@paramfilePathfilepath
*/
publicstaticvoidwrite(StringfilePath){
FileWriterfw=null;
try{
fw=newFileWriter(newFile(filePath));
for(inti=1;i<=50;i++){
fw.append(String.valueOf(i));
}
fw.flush();
}catch(IOExceptione){
e.printStackTrace();
}
if(fw!=null){
try{
fw.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}

⑧ java中字节流读写和字符流读写怎么理解

字节流与字符流主要的区别是他们的的处理方式
字节流是最基本的,所有的InputStream和OutputStream的子类都是,主要用在处理二进制数据,它是按字节来处理的
但实际中很多的数据是文本,又提出了字符流的概念,它是按虚拟机的encode来处理,也就是要进行字符集的转化
这两个之间通过 InputStreamReader,OutputStreamWriter来关联,实际上是通过byte[]和String来关联
在实际开发中出现的汉字问题实际上都是在字符流和字节流之间转化不统一而造成的

在从字节流转化为字符流时,实际上就是byte[]转化为String时,
public String(byte bytes[], String charsetName)
有一个关键的参数字符集编码,通常我们都省略了,那系统就用操作系统的lang
而在字符流转化为字节流时,实际上是String转化为byte[]时,
byte[] String.getBytes(String charsetName)
也是一样的道理

⑨ java的几种IO流读取文件方式

一、超类:


字节流: InputStream(读入流) OutputStream(写出流)


字符流: Reader(字符 读入流) Writer (字符写出流)

二、文件操作流


字节流: FileInputStream ,FileOutputStream


字符流: FileReader, FileWriter(用法与字节流基本相同,不写)

//1.指定要读 的文件目录及名称


File file =new File("文件路径");


//2.创建文件读入流对象


FileInputStream fis =new FileInputStream(file);


//3.定义结束标志,可用字节数组读取


int i =0 ;


while((i = fis.read())!=-1){


//i 就是从文件中读取的字节,读完后返回-1


}


//4.关闭流


fis.close();


//5.处理异常

//1.指定要写到的文件目录及名称


File file =new File("文件路径");


//2.创建文件读入流对象


FileOutputStream fos =new FileOutputStream(file);


//3.定义结束标志


fos.write(要写出的字节或者字节数组);


//4.刷新和关闭流


fos.flush();


fos.close();


//5.处理异常

三、缓冲流:


字节缓冲流: BufferedInputStream,BufferedOutputStream


字符缓冲流:BufferedReader ,BufferedWriter


缓冲流是对流的操作的功能的加强,提高了数据的读写效率。既然缓冲流是对流的功能和读写效率的加强和提高,所以在创建缓冲流的对象时应该要传入要加强的流对象。

//1.指定要读 的文件目录及名称


File file =new File("文件路径");


//2.创建文件读入流对象


FileInputStream fis =new FileInputStream(file);


//3.创建缓冲流对象加强fis功能


BufferedInputStream bis =new BufferedInputStream(fis);


//4.定义结束标志,可用字节数组读取


int i =0 ;


while((i = bis.read())!=-1){


//i 就是从文件中读取的字节,读完后返回-1


}


//5.关闭流


bis.close();


//6.处理异常

//1.指定要写到的文件目录及名称


File file =new File("文件路径");


//2.创建文件读入流对象


FileOutputStream fos =new FileOutputStream(file);


//3.创建缓冲流对象加强fos功能


BufferedOutputStream bos=new BufferedOutputStream(fos);


//4.向流中写入数据


bos.write(要写出的字节或者字节数组);


//5.刷新和关闭流


bos.flush();


bos.close();


//6.处理异常

四、对象流


ObjectInputStream ,ObjectOutputStream


不同于以上两种类型的流这里只能用字节对对象进行操作原因可以看上篇的编码表比照原理

ObjectOutputStream对象的序列化:


将java程序中的对象写到本地磁盘里用ObjectOutputStream


eg:将Person类的对象序列化到磁盘

  1. 创建Person类


    注1:此类要实现Serializable接口,此接口为标志性接口


    注2:此类要有无参的构造函数


    注3:一旦序列化此类不能再修改


    class Person implements Serializable{


    public Person(){}


    }


    2.创建对象流对象


    注:要增强功能可以将传入文件缓冲流


    ObjectOutputStream oos =new ObjectOutputStream(


    new FileOutputStream(new File("文件路径")));


    3.写入对象 ,一般会将对象用集合存储起来然后直接将集合写入文件


    List<Person> list =new ArrayList<>();


    list.add(new Person());


    ...(可以添加多个)


    oos.writeObject(list);


    4.关闭流,处理异常


    oos.flush();


    oos.close();

五、转换流:

这类流是用于将字符转换为字节输入输出,用于操作字符文件,属于字符流的子类,所以后缀为reader,writer;前缀inputstream,outputstream;

注 :要传入字节流作为参赛


InputStreamReader: 字符转换输出流


OutputStreamWriter:字符转换输入流

//1.获取键盘输入的字节流对象

inInputStream in =Stream.in;

/*2.用转换流将字节流对象转换为字符流对象,方便调用字符缓冲流的readeLine()方法*/


InputStreamReader isr =new InputStreamReader(in);


/*5.创建字符转换输出流对象osw,方便把输入的字符流转换为字节输出到本地文件。*/


OutputStreamWriter osw =new OutputStreamWriter(new
FileOutputStream(new File("文件名")));



/*3.现在isr是字符流,可以作为参数传入字符缓冲流中*/


BufferedReader br =new BufferedReader(isr);

/*4.可以调用字符缓冲流br的readLine()方法度一行输入文本*/


String line =null;


while((line =br.readLine()){


osw.write(line);//osw是字符流对象,可以直接操作字符串

}



注:InputStreamReader isr =new InputStreamReader(new "各种类型的字节输入流都行即是:后缀为InputStream就行");


OutputStreamWriter osw =new OutputStreamWriter(new
"后缀为OutputStream就行");

六、区别记忆


1.对象流是可以读写几乎所有类型的只要是对象就行,而字节字符流,只能读写单个字节字符或者字节字符数组,以上没有读写字节字符数组的;注意对象流只有字节流!


2.字符和字节循环读入的结束条件int i=0; (i =fis.read())!=-1
用字符数组复制文件(fr 读入流 ,fw写出流),字节流也是相同的用法

int i = 0; char[] c = new char[1024];


while((i = fr.reade()) !=-1)){


fw.write(c,0,i);


}

123456

3.对象流里面套缓冲流的情景:


new ObjectInputStream(new BufferedInputStream(new FileInputStream(new File(“文件路径”))));

4.记忆流及其功能的方法:


前缀表示功能,后缀表示流的类型;


比如说FileInputStream 前缀:File,表示操作的磁盘,后缀:intputstream,表示是字节输入流。


同理 FileReader:表示操作文件的字符流


ObjectInputStream :操作对象的字节输入流

5.拓展:获取键盘输入的字符的缓冲流的写法:


new BufferedReader(new InputStreamReader(System.in)));


将字节以字符形式输出到控制台的字符缓冲流的写法:


new BufferedWriter( new OutputStreamWriter(System.out))

⑩ java字节流 一次可以读一行 字符流 一次读一个是吗

JAVA字节流 是每次从文件中读取单个字节 字符流是每次读出1个字符 相当于每次读出2个字节
FileInputStream fs=new FileInputStream(路径); 这是一个字符流
InputStreamReader ir=new InputStreamReader( fs) 这是一个字符流 fs 为字节流 这个类就是把字节流转化为字符流;
字符流 就是为了方便读取文字和符号的 都知道中文汉字要2个字节才能存储 如果一次读出1个字节 在转化为中文 就会出乱码了 ;
这些问题你都可以通过查询API文档找到答案的

阅读全文

与java字符流读取相关的资料

热点内容
加强数字货币国际信息编译能力 浏览:584
购买的app会员怎么退安卓手机 浏览:891
程序员的种类及名称 浏览:292
美国程序员薪资 浏览:12
黑石通汇证券服务器什么时候到期 浏览:393
东方财富app里我的关注怎么看 浏览:749
bm3d单反级降噪算法 浏览:457
华为安卓机激活时间怎么查询 浏览:850
如何用优盘重装服务器系统 浏览:317
日本结婚三代算法 浏览:920
皓强工具解压步骤 浏览:690
部队抗洪抢险命令范文 浏览:888
欧姆龙plc编程软件使用教程 浏览:594
ai文件pdf 浏览:912
腾讯云服务器挂载混合云 浏览:758
智能小车用什么单片机 浏览:463
java怎么给窗口关闭 浏览:940
列举51单片机的寻址方式 浏览:706
剪辑app怎么写长篇文字 浏览:400
app专属流量过月租怎么不更新 浏览:656