JAVA TXT字符流复制代码问题

Python014

JAVA TXT字符流复制代码问题,第1张

File file=new File("E:\\1.txt")//创建文件对象,

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

BufferedInputStream reader=null

BufferedOutputStream write=null //该类实现缓冲的输出流。通过设置这种输出流,应用程序就可以将各个字节写入底层输出流中,而不必针对每次字节写入调用底层系统。

try

{

fread = new FileInputStream(file)//将文件对象添加到文件的输入流,也就是你要从你的数据源开始读取数据

reader=new BufferedInputStream(fread)//将字节流对象添加到缓存区中,这样效率要高一点

String str=null//初始化字符串这样保存的是读取的一行的数据

write=new BufferedOutputStream(new FileOutputStream(new File("E:\\2.txt")))//创建的是输出流缓存 请要输出的目的地添加到缓存区中,

byte b[]=new byte[1024]//定义每次读取的字节的范围,也是存储数据的容器

int i=0

while((i=reader.read(b))!=-1) //下一个数据字节,如果到达流末尾,则返回 -1。

{

write.write(b)//开始写入数据

}

}

catch (FileNotFoundException e) //如果没有文件打印该异常

{

e.printStackTrace()

}

catch (IOException e) //如果出现io异常 也就处理异常

{

e.printStackTrace()

}

finally//最后不管读取还是没读取成功都释放资源

{

try

{

write.close()//关闭缓存区,关闭缓存区会自动关闭相应的io流

reader.close()

}

catch (IOException e)

{

e.printStackTrace()

}

}

主要是用到java里面的i/o流。代码例子如下:

import java.io.BufferedReader

import java.io.File

import java.io.FileInputStream

import java.io.FileNotFoundException

import java.io.FileOutputStream

import java.io.FileWriter

import java.io.IOException

import java.io.InputStream

import java.io.InputStreamReader

/**

* java读写文件,复制文件

* 读取d:/1.txt文件内容,写入f:/text.txt文件中.

* @author young

*

*/

public class FileWriterTest {

// 读写文件

public static void rwFile(){

FileWriter fw = null

BufferedReader br = null

try {

fw = new FileWriter("f:\\text.txt", true)

br = new BufferedReader(new InputStreamReader(

new FileInputStream("d:\\1.txt"), "UTF-8"))

String line = null

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

System.out.println("文件内容: " + line)

fw.write(line)

fw.flush()

}

br.close()

} catch (FileNotFoundException e) {

e.printStackTrace()

} catch (IOException e) {

e.printStackTrace()

} finally {

if (fw != null) {

try {

fw.close()

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace()

}

}

}

}

public static void main(String[] args) {

rwFile()

}

}

首先在D盘新建文件1.txt,输入任意内容。然后执行java代码即可。

你可以新建一个工程,也就是像前面两位所说的:

打开eclipse,file—new—java project,输入工程名。

然后如果你上面的那些代码已保存成.java文件,那么就直接拖到工程里面就可以了。

如果没有的话,就照前面那位说的:

new—class,建立一个类,类的名字就是Best,然后把你上面的代码复制过去就可以了。