黑马程序员技术交流社区
标题:
对代码如何优化
[打印本页]
作者:
alax
时间:
2014-5-19 19:58
标题:
对代码如何优化
package com.io;
import java.io.*;
public class Copyctod {
public static void main(String[] args) throws Exception{
FileReader fr=null;
FileWriter fw=null;
try {
fr=new FileReader("c:\\a.txt");
fw=new FileWriter("d:\\d.txt",true);
char[] buf=new char[1024];
int num=0;
while((num=fr.read(buf))!=-1)
{
fw.write(buf);
}
} catch (Exception e) {
// TODO Auto-generated catch block
throw new RuntimeException("读写失败");
}finally{
try {
if(fr!=null)
fr.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
fw.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
作者:
skill20
时间:
2014-5-19 20:11
public static void copy(){
File file = new File("c:\\a.txt");
PrintWriter pw = null;
Scanner sc = null;
try {
sc = new Scanner(file);
while(sc.hasNext()){
String str = sc.nextLine();
pw = new PrintWriter(new FileWriter("d:\\d.txt"),true);
pw.println(str);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(pw != null)
pw.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(sc != null)
sc.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
复制代码
作者:
周俊波
时间:
2014-5-19 20:26
public class Copyctod {
public static final String file1 = "c:\\a.txt";
public static final String file2 = "d:\\d.txt";
public void copy(String file1,String file2) {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader(file1);
fw = new FileWriter(file2, true);
char[] buf = new char[1024];
int num = 0;
while ((num = fr.read(buf)) != -1) {
fw.write(buf);
}
} catch (Exception e) {
throw new RuntimeException("读写失败");
} finally {
try {
if (fr != null)
fr.close();
if(fw != null) {
fr.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
Copyctod c = new Copyctod();
c.copy(file1, file2);
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2