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();
這些方法可以根據具體的需求選擇適合的方式進行文件傳輸。