代码实现了三个方法包括
readFile
writeFile
copyFile
package 读入写入拷贝;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Random;
public class Text {
public static void readFile(String filename) {
FileInputStream fi = null;
try {
fi = new FileInputStream(new File(filename));
byte buffer[] = new byte[1024];
int count = 0;
while((count = fi.read(buffer))!=-1) {
System.out.println("一共输入 "+count+" 个字节");
System.out.println("读取文件原内容是:");
System.out.println(new String(buffer,0,count,"UTF-8"));
System.out.println("读取字节码为:");
for(int i=0;i<count;i++) {
System.out.print(buffer[i]+" ");
}
}
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
public static void writefile(String text,File filename) {
FileOutputStream fo = null;
byte buffer[]=new byte[100];
for (int i = 0;i<100;i++)
{
buffer[i] = (byte)new Random().nextInt(100);
}
try {
fo = new FileOutputStream(filename);
try {
fo.write(buffer);
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
// byte b[]=null;
// try {
// b=text.getBytes("UTF-8");
// try {
// fo = new FileOutputStream(filename);
// } catch (FileNotFoundException e) {
// // TODO 自动生成的 catch 块
// e.printStackTrace();
// }
// fo.write(b);
// if(fo!= null)
// {
// fo.close();
// }
// } catch (UnsupportedEncodingException e) {
// TODO 自动生成的 catch 块
// e.printStackTrace();
// } catch (IOException e) {
// // TODO 自动生成的 catch 块
// e.printStackTrace();
// }
}
public static void filecopy(File source,File destination) {
byte buffer[] = new byte[1024];
FileInputStream fi = null;
FileOutputStream fo= null;
int count = 0;
try {
fi = new FileInputStream(source);
fo = new FileOutputStream(destination);
while((count = fi.read(buffer))!=-1) {
fo.write(buffer, 0, count);
}
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
readFile("D:/tools/mydream.txt");
String text =null;
//String text = "我爱茜茜茜茜";
writefile(text,new File("D:/tools/mydata.txt"));
filecopy(new File("D:/tools/MyDream.txt"), new File("D:/tools/newMyDream.txt"));
}
}
简单的输入输出流操作
如有错误,欢迎指正。