分别使用 FileInputStream和FileOutputStream、BufferedInputStream和BufferedOutputStream、FileReader和
1个回答
展开全部
FileInputStream与BufferedInputStream区别:
FileInputStream是字节流,BufferedInputStream是字节缓冲流,使用BufferedInputStream读资源比FileInputStream读取资源的效率高(BufferedInputStream的read方法会读取尽可能多的字节),且FileInputStream对象的read方法会出现阻塞;
FileInputStream与FileReader区别:
FileInputStream是字节流,FileReader是字符流,用字节流读取中文的时候,可能会出现乱码,而用字符流则不会出现乱码,而且用字符流读取的速度比字节流要快;
FileInputStream是字节流,BufferedInputStream是字节缓冲流,使用BufferedInputStream读资源比FileInputStream读取资源的效率高(BufferedInputStream的read方法会读取尽可能多的字节),且FileInputStream对象的read方法会出现阻塞;
FileInputStream与FileReader区别:
FileInputStream是字节流,FileReader是字符流,用字节流读取中文的时候,可能会出现乱码,而用字符流则不会出现乱码,而且用字符流读取的速度比字节流要快;
追问
详细代码
追答
FileStreamDemo.java
import java.io.*;
public class FileStreamDemo {
public static void main(String[] args) {
try {
FileInputStream in = new FileInputStream("FileCopy.java");
FileOutputStream out = new FileOutputStream("fileoutput.txt");
byte[] bytearray = new byte[1024];
do {
in.read(bytearray, 0, 1024);
out.write(bytearray);
} while (in.available() > 0);
in.close();
out.close();
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
BufferedStreamDemo.java
import java.io.*;
public class FileStreamDemo {
public static void main(String[] args) {
try {
FileInputStream in = new FileInputStream("FileCopy.java");
FileOutputStream out = new FileOutputStream("bufferoutput.txt");
BufferedInputStream bufferedIn = new BufferedInputStream(in);
BufferedOutputStream bufferedOut = new BufferedOutputStream(out);
byte[] data = new byte[1];
while (bufferedIn.read(data) != -1) {
bufferedOut.write(data);
}
bufferedOut.flush();
bufferedIn.close();
bufferedOut.close();
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
import java.io.*;
class CopyText
{
public static void main(String[] args) throws IOException
{
FileReader fr = new FileReader("FileCopy.java");
FileWriter fw = new FileWriter("filewriter.txt");
char[] arr = new char[1024];
int num = 0;
while((num=fr.read(arr))!=-1)
{
fw.write(arr,0,num);
}
fw.close();
fr.close();
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询