「java缓冲流生成文件」java文件流保存成文件

博主:adminadmin 2023-01-02 11:18:09 766

今天给各位分享java缓冲流生成文件的知识,其中也会对java文件流保存成文件进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

java缓冲流读写数据

         ---  下面都是以字节流方式操作  ---

//读数据:

BufferedInputStream bis = new BufferedInputStream(new FileInputStream("xx.xx"));

byte[] b = new byte[1024];

int len = 0;

while((len=bis.read(b))!-1){

    //这样就读取并输出了,如果是别的文件的话乱码,因为二进制文件

    System.out.println(new String(b,0,len)); 

}

bis.close();//关闭流,节省资源

//写数据:

BufferedOutputStream bos = new BufferedOutputStream(new FileOuputStream("xx.xx"));

//使用缓冲区写二进制字节数据

bos.write("xxxxx".getBytes());

bos.close();//关闭流,节省资源

如果字符流的话就是:

BufferedReader  //读取

BufferedWriter    //写入

Java中使用基于字符的缓冲流读文件、写文件需要用到哪几个类?

import java.io.*;

public class Test {

    public static void main(String[] args) throws IOException {

        // 写文件至少需要 BufferedWriter、FileWriter 两个类

        try (BufferedWriter bw = new BufferedWriter(new FileWriter("d:/test.txt"))) {

            for (int i = 0; i  10; i++) {

                bw.write(i + "");

                // 换行

                bw.newLine();

            }

        }

        // 读文件至少需要 BufferedReader、FileReader 两个类

        try (BufferedReader br = new BufferedReader(new FileReader("d:/test.txt"))) {

            String line;

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

                System.out.println(line);

            }

        }

    }

}

java缓冲流写入TXT文件乱码问题

设置成带编码的写入试试:

int a=input.nextInt();

String encoding="utf-8"; // 指定文件写入时采用的字符集(Windows默认是GBK)

ps = new java.io.PrintStream(fout, true, encoding);

java缓冲流BufferWriter的原理跟提高效率原因

不带缓冲的流的工作原理:它读取到一个字节/字符,就向用户指定的路径写出去 读一个写一个 所以就慢了

带缓冲的流的工作原理:读取到一个字节/字符,先不输出,等凑足了缓冲的最大容量后一次性写出去,从而提高了工作效率

举个现实生活中的例子:假设你是一个快递员,不带缓冲的流就像快递公司给你一份快递你就跑一次,而带缓冲的流就像快递公司给你一份快递,你先不去,等攒攒多一起送,试想一下,是不是效率提高了?

java 中简述使用流进行读写文本文件的步骤?

一、Java IO学习基础之读写文本文件

Java的IO操作都是基于流进行操作的,为了提高读写效率一般需要进行缓冲。

简单的示例程序如下:

/**

* 读出1.txt中的内容,写入2.txt中

*

*/

import java.io.*;

public class ReadWriteFile{

public static void main(String[] args){

try{

File read = new File("c:\\1.txt");

File write = new File("c:\\2.txt");

BufferedReader br = new BufferedReader(

new FileReader(read));

BufferedWriter bw = new BufferedWriter(

new FileWriter(write));

String temp = null;

temp = br.readLine();

while(temp != null){

//写文件

bw.write(temp + "\r\n"); //只适用Windows系统

//继续读文件

temp = br.readLine();

}

bw.close();

br.close();

}catch(FileNotFoundException e){ //文件未找到

System.out.println (e);

}catch(IOException e){

System.out.println (e);

}

}

}

以上是一个比较简单的基础示例。本文上下两部分都是从网上摘抄,合并在一起,方便下自己以后查找。

二、Java IO学习笔记+代码

文件对象的生成和文件的创建

/*

* ProcessFileName.java

*

* Created on 2006年8月22日, 下午3:10

*

* 文件对象的生成和文件的创建

*/

package study.iostudy;

import java.io.*;

public class GenerateFile

{

public static void main(String[] args)

{

File dirObject = new File("d:\\mydir");

File fileObject1 = new File("oneFirst.txt");

File fileObject2 = new File("d:\\mydir", "firstFile.txt");

System.out.println(fileObject2);

try

{

dirObject.mkdir();

}catch(SecurityException e)

{

e.printStackTrace();

}

try

{

fileObject2.createNewFile();

fileObject1.createNewFile();

}catch(IOException e)

{

e.printStackTrace();

}

}

}

文件名的处理

/*

* ProcessFileName.java

*

* Created on 2006年8月22日, 下午3:29

*

* 文件名的处理

*/

package study.iostudy;

import java.io.*;

/*

* 文件名的处理

* String getName(); 获得文件的名称,不包含文件所在的路径。

* String getPath(); 获得文件的路径。

* String getAbsolutePath(); 获得文件的绝对路径。

* String getParent(); 获得文件的上一级目录的名称。

* String renameTo(File newName); 按参数中给定的完整路径更改当前的文件名。

* int compareTo(File pathName); 按照字典顺序比较两个文件对象的路径。

* boolean isAbsolute(); 测试文件对象的路径是不是绝对路径。

*/

public class ProcesserFileName

{

public static void main(String[] args)

{

File fileObject1 = new File("d:\\mydir\\firstFile.txt");

File fileObject2 = new File("d:\\firstFile.txt");

boolean pathAbsolute = fileObject1.isAbsolute();

System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * ");

System.out.println("There are some information of fileObject1's file name:");

System.out.println("fileObject1: " + fileObject1);

System.out.println("fileObject2: " + fileObject2);

System.out.println("file name: " + fileObject1.getName());

System.out.println("file path: " + fileObject1.getPath());

System.out.println("file absolute path: " + fileObject1.getAbsolutePath());

System.out.println("file's parent directory: " + fileObject1.getParent());

System.out.println("file's absoulte path: " + pathAbsolute);

int sameName = fileObject1.compareTo(fileObject2);

System.out.println("fileObject1 compare to fileObject2: " + sameName);

fileObject1.renameTo(fileObject2);

System.out.println("file's new name: " + fileObject1.getName());

}

}

测试和设置文件属性

/*

* SetterFileAttribute.java

*

* Created on 2006年8月22日, 下午3:51

*

* 测试和设置文件属性

*/

package study.iostudy;

import java.io.*;

public class SetterFileAttribute

{

/*

* File类中提供的有关文件属性测试方面的方法有以下几种:

* boolean exists(); 测试当前文件对象指示的文件是否存在。

* boolean isFile(); 测试当前文件对象是不是文件。

* boolean isDirectory(); 测试当前文件对象是不是目录。

* boolean canRead(); 测试当前文件对象是否可读。

* boolean canWrite(); 测试当前文件对象是否可写。

* boolean setReadOnly(); 将当前文件对象设置为只读。

* long length(); 获得当前文件对象的长度。

*/

public static void main(String[] args)

{

File dirObject = new File("d:\\mydir");

File fileObject = new File("d:\\mydir\\firstFile.txt");

try

{

dirObject.mkdir();

fileObject.createNewFile();

}catch(IOException e)

{

e.printStackTrace();

}

System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * ");

System.out.println("there are some information about property of file object:");

System.out.println("file object : " + fileObject);

System.out.println("file exist? " + fileObject.exists());

System.out.println("Is a file? " + fileObject.isFile());

System.out.println("Is a directory?" + fileObject.isDirectory());

System.out.println("Can read this file? " + fileObject.canRead());

System.out.println("Can write this fie? " + fileObject.canWrite());

long fileLen = fileObject.length();

System.out.println("file length: " +fileLen);

boolean fileRead = fileObject.setReadOnly();

System.out.println(fileRead);

System.out.println("Can read this file? " + fileObject.canRead());

System.out.println("Can write this fie? " + fileObject.canWrite());

System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * ");

}

}

文件操作方法

/*

* FileOperation.java

*

* Created on 2006年8月22日, 下午4:25

*

* 文件操作方法

*/

package study.iostudy;

import java.io.*;

/*

* 有关文件操作方面的方法有如下几种:

* boolean createNewFile(); 根据当前的文件对象创建一个新的文件。

* boolean mkdir(); 根据当前的文件对象生成一目录,也就是指定路径下的文件夹。

* boolean mkdirs(); 也是根据当前的文件对象生成一个目录,

* 不同的地方在于该方法即使创建目录失败,

* 也会成功参数中指定的所有父目录。

* boolean delete(); 删除当前的文件。

* void deleteOnExit(); 当前Java虚拟机终止时删除当前的文件。

* String list(); 列出当前目录下的文件。

*/

public class FileOperation

* 找出一个目录下所有的文件

package study.iostudy;

import java.io.*;

public class SearchFile

{

public static void main(String[] args)

{

File dirObject = new File("D:\\aa");

Filter1 filterObj1 = new Filter1("HTML");

Filter2 filterObj2 = new Filter2("Applet");

System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

System.out.println("list HTML files in directory: " + dirObject);

String[] filesObj1 = dirObject.list(filterObj1);

for (int i = 0; i filesObj1.length; i++)

{

File fileObject = new File(dirObject, filesObj1[i]);

System.out.println(((fileObject.isFile())

? "HTML file: " : "sub directory: ") + fileObject);

}

System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

String[] filesObj2 = dirObject.list(filterObj2);

for (int i = 0; i filesObj2.length; i++)

{

File fileObject = new File(dirObject, filesObj2[i]);

System.out.println(((fileObject.isFile())

? "htm file: " : "sub directory: ") + fileObject);

}

}

}

class Filter1 implements FilenameFilter

{

String fileExtent;

Filter1(String extentObj)

{

fileExtent = extentObj;

}

public boolean accept(File dir, String name)

{

return name.endsWith("." + fileExtent);

}

}

class Filter2 implements FilenameFilter

{

String fileName;

Filter2(String fileName)

{

this.fileName = fileName;

字符流处理

* ProcesserCharacterStream.java

* 字符流处理

*

* java.io包中加入了专门用于字符流处理的类,这些类都是Reader和Writer类的子类,

* Reader和Writer是两个抽象类,只提供了一系列用于字符流处理的接口,不能生成这

* 两个类的实例。

* java.io包中用于字符流处理的最基本的类是InputStreamReader和OutputStreamWriter,

* 用来在字节流和字符流之间作为中介。

*

* 下面是InputStreamReader类和OutputStreamWriter类的常用方法:

*

* public InputStreamReader(InputStream in)

* 根据当前平台缺省的编码规范,基于字节流in生成一个输入字符流。

* public InputStreamReader(InputStream in, String sysCode)throws UnSupportedEncodingException

* 按照参数sysCode指定的编码规范,基于字节流in构造输入字符流,如果不支持参数sysCode中指定的编码规范,就会产生异常。

* public OutputStreamWriter(OutputStream out)

* 根据当前平台缺省的编码规范,基于字节流out生成一个输入字符流。

* public OutputStreamWriter(OutputStream out, String sysCode) throws UnsupportedEncodingException

* 按照参数sysCode指定的编码规范,基于字节流out构造输入字符流,如果不支持参数sysCode中指定的编码规范,就会产生异常。

* public String getEncoding()

* 获得当前字符流使用的编码方式。

* public void close() throws IOException

* 用于关闭流。

* public int read() throws IOException

* 用于读取一个字符。

* public int read(char[] cbuf, int off, int len)

* 用于读取len个字符到数组cbuf的索引off处。

* public void write(char[] cbuf, int off, int len) throws IOException

* 将字符数组cbuf中从索引off处开始的len个字符写入输出流。

* public void write(int c) throws IOException

* 将单个字符写入输入流。

* public void write(String str, int off, int len) throws IOException

* 将字符串str中从索引off位置开始的ltn个字符写入输出流。

*

* 此外,为了提高字符流处理的效率,在Java语言中,引入了BufferedReader和BufferWriter类,这两个类对字符流进行块处理。

* 两个类的常用方法如下:

* public BufferedReader(Reader in)

* 用于基于普通字符输入流in生成相应的缓冲流。

* public BufferedReader(Reader in, int bufSize)

* 用于基于普通字符输入流in生成相应的缓冲流,缓冲区大小为参数bufSize指定。

* public BufferedWriter(Writer out)

* 用于基于普通字符输入流out生成相应的缓冲流。

* public BufferedWriter(Writer out, int bufSize)

* 用于基于普通字符输入流out生在相应缓冲流,缓冲流大小为参数bufSize指定。

* public String readLine() throws IOException

* 用于从输入流中读取一行字符。

* public void newLine() throws IOException

* 用于向字符输入流中写入一行结束标记,值得注意的是,该标记不是简单的换行符"\n",而是系统定义的属性line.separator。

在上面的程序中,我们首先声明了FileInputStream类对象inStream和

* FileOutputStream类的对象outStream,接着声明了BufferInputStream

* 类对象bufObj、BufferedOutputStream类对象bufOutObj、

* DataInputStream类对象dataInObj以及PushbackInputStream类对象pushObj,

* 在try代码块中对上面这些对象进行初始化,程序的目的是通过BufferedInputStream

* 类对象bufInObj和BufferedOutputStream类对象bufOutObj将secondFile.txt

* 文件中内容输出到屏幕,并将该文件的内容写入thirdFile.txt文件中,值得注意的是,

* 将secondFile.txt文件中的内容输出之前,程序中使用

* "System.out.println(dataInObj.readBoolean());" 语句根据readBoolean()结果

* 输出了true,而secondFile.txt文件开始内容为“Modify”,和一个字符为M,

* 因此输出的文件内容没有“M”字符,thirdFile.txt文件中也比secondFile.txt

* 文件少第一个字符“M”。随后,通过PushbackInputStream类对象pushObj读取

* thirdFile.txt文件中的内容,输出读到的字符,当读到的不是字符,输出回车,将字符

* 数组pushByte写回到thirdFile.txt文件中,也就是“ok”写回文件中。

* 对象串行化

* 对象通过写出描述自己状态的数值来记录自己,这个过程叫做对象串行化。对象的寿命通

* 常是随着生成该对象的程序的终止而终止,在有些情况下,需要将对象的状态保存下来,然后

* 在必要的时候将对象恢复,值得注意的是,如果变量是另一个对象的引用,则引用的对象也要

* 串行化,串行化是一个递归的过程,可能会涉及到一个复杂树结构的串行化,比如包括原有对

* 象,对象的对象等。

* 在java.io包中,接口Serializable是实现对象串行化的工具,只有实现了Serializable

* 的对象才可以被串行化。Serializable接口中没有任何的方法,当一个类声明实现Seriali-

* zable接口时,只是表明该类遵循串行化协议,而不需要实现任何特殊的方法。

* 在进行对象串行化时,需要注意将串行化的对象和输入、输出流联系起来,首先通过对

* 象输出流将对象状态保存下来,然后通过对象输入流将对象状态恢复。

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类的对象序列化到磁盘

创建Person类

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

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

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

class Person implements Serializable{

public Person(){}

}

2.创建对象流对象

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

ObjectOutputStream oos =new ObjectOutputStream(

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

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

ListPerson 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文件流保存成文件的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。