我编写了下面的代码来复制文件及其内容。
static void copyFile(File inFile, String destination) {
if (inFile.isFile()) {
try {
String str = destination + "//" + inFile.getName();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(inFile),"UTF-8"));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(str), false), "UTF-8"));
String line;
try {
while((line = br.readLine()) != null) {
bw.write(line);
System.out.println(line);
}
} catch (IOException ex) {
Logger.getLogger(JavaApplication10.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(JavaApplication10.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(JavaApplication10.class.getName()).log(Level.SEVERE, null, ex);
}
} else if( inFile.isDirectory()) {
String str = destination + "\\" + inFile.getName();
File newDir = new File( str );
newDir.mkdir();
for( File file : inFile.listFiles())
copyFile(file, newDir.getAbsolutePath());
}
}
代码按预期在目标位置创建文件,但 .txt
文件为空。进入while循环的部分
bw.write(line);
不起作用
System.out.println(line);
有效。
最佳答案
您需要关闭您的Writer
才能让他刷新流。这可以使用较新的 try with ressources 方法来完成(首选):
String str = destination + "//" + inFile.getName();
// note the paranthesis here, notfing that this is has to be closed after leaving the try block.
try (
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(inFile), "UTF-8"));
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(new File(str), false), "UTF-8"))) {
String line;
try {
while ((line = br.readLine()) != null) {
bw.write(line);
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
或者使用finally block :
BufferedWriter bw = null;
BufferedReader br = null;
try {
String str = destination + "//" + inFile.getName();
br = new BufferedReader(new InputStreamReader(new FileInputStream(inFile), "UTF-8"));
bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(new File(str), false), "UTF-8"));
String line;
try {
while ((line = br.readLine()) != null) {
bw.write(line);
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
} finally {
try {
if(bw != null)
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (br != null)
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
此外,IDE 或编译器应该警告您不要关闭它们。
关于java - BufferedReader 不复制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39487009/