我已经制作了以下代码来复制文件及其内容。
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);
作品。
答案 0 :(得分:1)
您需要关闭1.6
才能让他冲洗流。这可以使用ressources方法(首选)进行更新的尝试:
Writer
或使用finally块:
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();
}
另外,IDE或编译器应警告您不要关闭它们。
答案 1 :(得分:0)
写完后忘记调用bw.flush()方法;
while((line = br.readLine()) != null ){
bw.write(line );
System.out.println( line );
}
bw.flush();
缓冲io记住调用flush方法;
答案 2 :(得分:0)
你可以试试这个
FileWriter fw = new FileWriter(inFile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(line);