package com.yang;
import org.junit.Test;
import java.io.*;
/**
* FileInputstream和FileOutputStream的使用
*/
public class FileReaderWriterTest {
/**
* 读入流
* @throws IOException
*/
@Test
public void testFileReader() throws IOException {
//造文件
File file=new File("file.txt");
//造流
FileInputStream fis=new FileInputStream(file);
//读取数据
// 字节数组
byte[]buffer=new byte[20];
int len;
while ((len=fis.read(buffer))!=-1){
String str=new String(buffer,0,len);
System.out.println(str);
}
fis.close();
}
}
读取图片
文件用字节流,非文件用字符流
package com.yang;
import org.junit.Test;
import java.io.*;
/**
* FileInputstream和FileOutputStream的使用
*/
public class FileReaderWriterTest {
/**
* 读入流
* @throws IOException
*/
@Test
public void testFileReader() throws IOException {
//造文件
File file=new File("1.png");
File file1=new File("2.png");
//造流
FileInputStream fis=new FileInputStream(file);
FileOutputStream out=new FileOutputStream(file1);
//读取数据
// 字节数组
byte[]buffer=new byte[5];
int len;
while ((len=fis.read(buffer))!=-1){
out.write(buffer,0,len);
}
fis.close();
out.close();
}
}
缓冲流实现非文本文件的复制
package com.yang;
import org.junit.Test;
import java.io.*;
/**
* FileInputstream和FileOutputStream的使用
*/
public class FileReaderWriterTest {
/**
* 读入流
* @throws IOException
*/
@Test
public void testFileReader() throws IOException {
//造文件
File file=new File("1.png");
File destFile=new File("2.png");
// 造节点流 文件流
FileInputStream fis=new FileInputStream(file);
FileOutputStream fos=new FileOutputStream(destFile);
// 造缓存流
BufferedInputStream bis=new BufferedInputStream(fis);
BufferedOutputStream bos=new BufferedOutputStream(fos);
// 字节数组
byte[]buffer=new byte[10];
int len;
while ((len=bis.read(buffer))!=-1){
bos.write(buffer,0,len);
}
bos.close();
bis.close();
}
}
缓冲流实现文件的复制
/**
* 读入流
* @throws IOException
*/
@Test
public void testFileReader() throws IOException {
BufferedReader br=new BufferedReader(new FileReader(new File("file.txt")));
BufferedWriter bw=new BufferedWriter(new FileWriter(new File("file1.txt")));
char[]cbf=new char[1024];
int len;
while ((len=br.read(cbf))!=-1){
bw.write(cbf,0,len);
bw.flush();
}
bw.close();
br.close();
}