Java文件流传输主要有以下几种方法:
// 读取源文件的字节数据
InputStream inputStream = new FileInputStream("source.txt");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
// 将字节数据写入目标文件
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
// 读取源文件的字符数据
Reader reader = new FileReader("source.txt");
char[] buffer = new char[1024];
int charsRead;
while ((charsRead = reader.read(buffer)) != -1) {
// 将字符数据写入目标文件
writer.write(buffer, 0, charsRead);
}
reader.close();
writer.close();
// 使用字节流传输
InputStream inputStream = new FileInputStream("source.txt");
OutputStream outputStream = new FileOutputStream("target.txt");
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
bufferedOutputStream.write(buffer, 0, bytesRead);
}
bufferedInputStream.close();
bufferedOutputStream.close();
// 使用字符流传输
Reader reader = new FileReader("source.txt");
Writer writer = new FileWriter("target.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
BufferedWriter bufferedWriter = new BufferedWriter(writer);
char[] buffer = new char[1024];
int charsRead;
while ((charsRead = bufferedReader.read(buffer)) != -1) {
bufferedWriter.write(buffer, 0, charsRead);
}
bufferedReader.close();
bufferedWriter.close();
这些方法可以根据具体的需求选择适合的方式进行文件传输。