比较经典的一个代码,使用FileInputStream读取文件A的字节,使用FileOutputStream写入到文件B。
public static void copy(String source, String dest, int bufferSize) {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(new File(source));
out = new FileOutputStream(new File(dest));
byte[] buffer = new byte[bufferSize];
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (Exception e) {
Log.w(TAG + ":copy", "error occur while copy", e);
} finally {
safelyClose(TAG + ":copy", in);
safelyClose(TAG + ":copy", out);
}
}
1.复制文件
//D:\app\文件练习\1.txt
FileInputStream in = new FileInputStream("D:\app\文件练习\1.txt");
FileOutputStream out = new FileOutputStream("D:\app\文件练习\2.txt",true);
byte [] buffer =new byte[100];
int len=0;
String string="\r\n";
while((len=in.read(buffer))!=-1){
out.write(buffer);
out.write(string.getBytes());
}
out.close();
in.close();
2.复制文件夹
public static void main(String[] args) throws IOException {
//D:\app\文件练习\1.txt
String string="D:\app\文件练习";
Two two = new Two();
two.copyList(string,string);
}
public void copyList(String src,String dest) throws IOException{
File in = new File(src);//源文件夹
File out = new File(dest+"复制");//目标文件夹
System.out.println(dest);
if(!out.exists()) {
out.mkdirs();
}
File[] listFiles = in.listFiles();
for(File file:listFiles) {
System.out.println(file.getName());
if(file.isFile()) {
Two two = new Two();
// String string=out.getAbsolutePath()+"\"+UUID.randomUUID()+file.getName();
// String string=out.getAbsolutePath()+"\"+System.currentTimeMillis()+file.getName();
String string=out.getAbsolutePath()+"\"+file.getName();
two.copyFile(file.getAbsolutePath(), string);
}
else {
String str=file.getName();
Two two = new Two();
two.copyList(file.getAbsolutePath(), out+"\"+str);
}
}
}
@SuppressWarnings("resource")
public void copyFile(String src,String dest) throws IOException {
FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dest);
byte []bs=new byte[1024];
int len=0;
while((len=in.read(bs))!=-1) {
out.write(bs);
// out.flush();
}
out.close();
in.close();
}
3.查找文件内容
//D:\app\文件练习\eng.txt
//统计总字符数
//某个字符出现的次数
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
String string="D:\app\文件练习\eng.txt";
File file = new File(string);
BufferedReader bf = new BufferedReader(new FileReader(file));
StringBuffer str = new StringBuffer();
String read = "";
while((read=bf.readLine())!=null) {
str.append(read);
}
System.out.println(str);
int count=0;
int index=0;
String a="a";
while((index=str.indexOf(a,index))!=-1) {
index=index+a.length();
count++;
}
System.out.println(count);
}
网友评论