package fileoutputstream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class CopyFileDemo {
public static void main(String[] args) throws Exception {
//封装数据源
FileInputStream fis = new FileInputStream("fos.txt");//fos.txt文件必须的存在
FileOutputStream fos = new FileOutputStream("write.txt");//write.txt文件可以先不存在
//复制数据()
byte[] bys = new byte[1024];
int len=0;
while((len=fis.read(bys))!=-1){
fos.write(bys,0,len);//一次写入一个字节数组
}
//释放资源
fos.close();
fis.close();
}
}
一次读取一个字节(字符),或者一次多去一个字节数组(字符数组)
package filereader;
import java.io.FileReader;
public class FileReader11 {
public static void main(String[] args) throws Exception {
// //方式一:一次读取一个字节
// FileReader reader = new FileReader("fos.txt");
//
// int by = 0;
// while((by=reader.read())!=-1){
System.out.println(by);
// System.out.print((char)by);
// }
// reader.close();
//方式二:一次读取一个字节数组
FileReader reader2 = new FileReader("fos.txt");
char[] ch = new char[5];
// byte[] bys = new byte[1024];
int len=0;
while((len=reader2.read(ch))!=-1){
System.out.println(new String(ch,0,len));
}
reader2.close();
}
}
最终版把读取的文件显示在控制台:
package fileoutputstream;
import java.io.FileInputStream;
public class FileOutputStream4 {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("fos.txt");
//最終版代碼
//数组的长度一般是1024或者1024的整数倍
byte[] bys = new byte[1024];
int len=0;
while((len=fis.read(bys))!=-1)
{
System.out.println(new String(bys,0,len));//new String是把字節數組转为字符串
}
}
}