日期:2014-05-20 浏览次数:21062 次
import java.io.*;
class WriteTest
{
public static void main(String[] args)
{
FileOutputStream fos=null;
FileInputStream fis=null;
try
{
fos=new FileOutputStream("c:\\2.txt");
fis=new FileInputStream("c:\\1.txt");
byte[] buf=new byte[1024];
int len=0;
while((len=fis.read(buf))!=-1)
{
fos.write(buf,0,len); //fos.write(buf);
num++;
}
System.out.println("OK");
}
catch (IOException e)
{
throw new RuntimeException("复制文件失败");
}
finally
{
try
{
if(fis!=null)
fis.close();
}
catch (IOException e)
{
throw new RuntimeException("读取关闭失败");
}
try
{
if(fos!=null)
fos.close();
}
catch (IOException e)
{
throw new RuntimeException("写入关闭失败");
}
}
}
}
package io; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub byte[] b = new byte[15]; byte bnum = 110; for (int i = 0; i < b.length; i++) { b[i] = bnum++; } ByteArrayInputStream bi = new ByteArrayInputStream(b); FileOutputStream fos; try { System.out .println("-------------用write(byte[] b)来写入文件---------------"); fos = new FileOutputStream(new File("C:\\文件1.txt")); int i = 0; byte[] buffer = new byte[10]; System.out.println("写入数据如下:"); while ((i = bi.read(buffer)) > 0) { p(buffer); fos.write(buffer); } System.out .println("-------------用write(byte[] b,int off,int len)来写入文件---------------"); bi.reset(); fos = new FileOutputStream(new File("C:\\文件1.txt")); i = 0; buffer = new byte[10]; System.out.println("写入数据如下:"); while ((i = bi.read(buffer)) > 0) { p(buffer); fos.write(buffer, 0, i); } fos.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void p(byte[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print((char) arr[i] + ","); } System.out.println(); } }