本篇以一个复制文件的示例来演示一下JAVA的流处理。
代码示例:
package com.IO;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
/**
* 测试IO
* @author Administrator
*
*/
public class TestIO {
/**
* 字节流读取文件
* @param src
* @return
* @throws IOException
*/
public static String getFileContent1(String src) throws IOException{
String str ="";
File file = new File(src);
if(!file.exists())
return "1";
int len =0;
FileInputStream inputStream = new FileInputStream(file);
byte a[] = new byte[inputStream.available()];
while((len=inputStream.read(a))!=-1){
//转换为平台编码,否则会出现乱码
str+=new String(a,"GBK");
}
inputStream.close();
System.out.println(str);
return str;
}
/**
* 字节流包装成字符流在在输出
* @throws IOException
*/
public static String getFileContent(String src) throws IOException{
String str="";
File file = new File(src);
//判断是否是文件夹
if(!file.exists())
return "1";
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"GBK");
char b[] =new char[1024];
int len = 0;
while((len=inputStreamReader.read(b))!=-1){
str+= new String(b,0,len);
}
System.out.println(str);
inputStreamReader.close();
fileInputStream.close();
return str;
}
/**
*
* @param src 源路径
* @param souce 目标路径
* @throws IOException
*/
public static void copyInputS(String src,String target) throws IOException{
String fileName = "\\";
File targetFile = new File(target);
File srcFile = new File(src);
//判断源路径必须是文件,目标必须是路径
if(srcFile.isDirectory()){
System.out.println("源路径不是文件,不能复制");
return ;
}
if(!targetFile.exists()){
targetFile.mkdirs();
}
//获取需要复制的文件名字和后缀
fileName = src.substring(src.lastIndexOf("\\"));
//创建文件夹
//目标路径存在则直接创建文件
fileName=target+fileName;
System.out.println("复制之后的文件名字:"+fileName);
new File(fileName).createNewFile();
InputStream inputStream = new FileInputStream(srcFile);
OutputStream outputStream = new FileOutputStream(fileName);
int len=0;
byte a[] = new byte[inputStream.available()];
while((len= inputStream.read(a))!=-1){
outputStream.write(a);
}
outputStream.close();
inputStream.close();
}
public static void main(String[] args) {
String src = "D:\\test\\test.txt";
String target = "E:\\test\\";
try {
copyInputS(src,target);
//System.out.println(getFileContent1(src));
//System.out.println(getFileContent(src));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
src是源文件,target是目标路径,在示例中,读取文件的时候我使用的是字节流,在写入文件的时候,我使用的是字符流。
在JAVA里面,I/O大致就是这两种,字节流和字符流。