`

字符流和字节流

    博客分类:
  • java
阅读更多

字节流:InputStream,OutStream

字符流:Reader,Writer


字符流专门处理用来处理包含文字的文件,可以指定文件的编码方式

字节流可以指定一次传输的大小,常常用来处理图片,视屏等大文件

一般txt的编码方式是ACSII码,比如你写入"12abc",实际存入计算机的是81—82—97—98—99,的二进制

 

 

下面以两个例子来阐述字符流和字节流

 

字符流:

 

/**

 * 字符流方式,拷贝文件

 * @author Li Jia Xuan

 * @version 1.0

 * @since 2012-10-30

 * @time 上午10:53:32

 */

public class TestCopy {

/**

 * 

 * @param source

 * @param target

 */

public static void copy(String source, String target) {

if (!source.equals("") && !target.equals("")) {

File sourcefile = new File(source);

File targetfile = new File(target);

BufferedReader br = null;

BufferedWriter bw = null;

try {

br = new BufferedReader(new InputStreamReader(

new FileInputStream(sourcefile)));

// bw=new BufferedWriter(new FileWriter(targetfile));

bw = new BufferedWriter(new OutputStreamWriter(

new FileOutputStream(targetfile)));

String line = "";

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

bw.write(line);

}

bw.flush();

} catch (FileNotFoundException e) {

 

e.printStackTrace();

} catch (IOException e) {

 

e.printStackTrace();

} finally {

closeIO(br,bw);

}

}

}

/**

* 关闭流,一般采取先开后关、由外向内的原则

* @param br

* @param bw

*/

public static void closeIO(BufferedReader br,BufferedWriter bw){

if (bw != null) {

try {

bw.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

if (br != null) {

try {

br.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

 

}

}

}

字节流:
/**
 *利用字节流,实现对视屏音频文件的拷贝
 *@author Li Jia Xuan
 *@version 1.0
 *@since 2012-10-30
 *@time 上午11:42:48
 */
public class TestCopy1 {
public static  void copy(String source,String target){
InputStream is=null;
OutputStream os=null;
try {
is=new FileInputStream(source);
os=new FileOutputStream(target);
byte[] b=new byte[1024*1024];//1K的读取单位
for(int len=0;(len=is.read(b, 0, b.length))!=-1;){
os.write(b, 0, len);
}
os.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void closeIO(InputStream is,OutputStream os){
if(os!=null){
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(is!=null){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
备注:以上包名没有导入

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics