1.编码实现一个任意文件夹的拷贝:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class test1{
static String target = "D:/作业.txt";
static String source = "E:\\下载应用\\Atm";
public static void main(String[] args) {
File f1 = new File("E:\\\\下载应用\\\\Atm");
copy(f1);
}
public static void copy(File source) {
if (source.exists()) {
if (source.isFile()) {
String ss = source.getAbsolutePath();
ss = ss.replace( test1.source, test1.target);
try {
copyFile(source, new File(ss));
} catch (Exception e) {
e.printStackTrace();
}
} else if (source.isDirectory()) {
String ss = source.getAbsolutePath();
ss = ss.replace( test1.source, test1.target);
File tmp = new File(ss);
if (!tmp.exists())
tmp.mkdirs();
File[] children = source.listFiles();
if (children != null && children.length > 0) {
for (File temp : children)
copy(temp);
}
}
}
}
private static void copyFile(File source, File target) throws Exception {
try (InputStream is = new FileInputStream(source);
OutputStream os = new FileOutputStream(target);) {
byte[] buffer=new byte[8192];
int len=0;
while((len=is.read(buffer))>0) {
os.write(buffer,0,len);
}
}
}
}
2.统计一个文件calcCharNum.txt中各个字符出现次数:A(8),B(16),C(10)...,a(12),b(10),c(3)....,
括号内代表字符出现次数,要求按照出现次数从小到达排序输出。如果是回车符则按照空格符处理
public class ArrayList {
private CharNum[] arr;
private int count;
public ArrayList() {
this(10);
}
public ArrayList(int length) {
arr = new CharNum[length];
}
public void show() {
for(int i=0;i<count;i++) {
System.out.print(arr[i]+",");
}
}
public void sort() {
for(int i=1;i<count;i++) {
for(int k=0;k<count-i;k++) {
if(arr[k].big(arr[k+1])) {
CharNum tmp=arr[k];
arr[k]=arr[k+1];
arr[k+1]=tmp;
}
}
}
}
public void add(char ch) {
int exists=indexOf(ch);
if(exists>=0) {
arr[exists].addNum();
}else {
arr[count++]=new CharNum(ch);
if(count>=arr.length)
resize();
}
}
private void resize() {
CharNum[] res=new CharNum[arr.length*3/2];
for(int i=0;i<count;i++)
res[i]=arr[i];
this.arr=res;
}
private int indexOf(char ch) {
int pos=-1;
for(int i=0;i<count;i++) {
CharNum cn=arr[i];
if(cn.getCh()==ch) {
pos=i;
break;
}
}
return pos;
}
public class CharNum {
private char ch;
private int num;
public CharNum(char ch) {
this.ch = ch;
this.num = 1;
}
@Override
public String toString() {
return ch + "(" + num + ")";
}
public char getCh() {
return ch;
}
public void addNum() {
this.num++;
}
public boolean big(CharNum charNum) {
boolean res = false;
if (this.num > charNum.num)
res = true;
else if (this.num == charNum.num) {
res = this.ch > charNum.ch;
}
return res;
}
}
import java.io.FileReader;
import java.io.Reader;
public static void main(String[] args) throws Exception {
ArrayList list=new ArrayList();
try (Reader r = new FileReader("data/calcCharNum.txt")) {
int kk=-1;
while(true) {
kk=r.read();
if(kk==-1)
break;
if(kk=='\r'||kk=='\n'||kk=='\t')
kk=' ';
list.add((char)kk);
}
list.sort();
list.show();
}
}
}