Points

  1. 输出Java程序运行时间
1
2
3
4
long l=System.currentTimeMillis();
//Java Statements
//...
System.out.println(System.currentTimeMillis()-l+" ms");
  1. 按行读入文本文件
1
2
3
4
5
6
7
8
9
10
11
12
13
import java.io.*;
try{
BufferedReader reader=new BufferedReader(new FileReader(filePath));
String line=reader.readLine();
while(line!=null){
//statements
line=reader.readLine();
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
  1. 修改文本文件中的内容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.io.*;
public class FileTool{
//修改homeDir中的txt文件,包括子目录下的txt文件,将orgStr改为targetStr
public void replaceTxtFileContent(String homeDir,String orgStr,String targetStr) {
File file=new File(homeDir);
if(file.isDirectory()) {
for(String str:file.list()) {
if(str.endsWith(".txt")) {
String filename=homeDir+str+"/";
File temp=new File(filename);
try {
BufferedReader reader=new BufferedReader(new FileReader(filename));
String line=reader.readLine();
//不能直接对line进行修改,因为line是reader读出的数据,不能直接利用字符串修改
String newLine=line.replaceAll(orgStr, targetStr);
//需要新建一个字符串,将orgStr替换为targetStr
//新建文件输出流
FileOutputStream os=new FileOutputStream(temp);
OutputStreamWriter writer=new OutputStreamWriter(os,"UTF-8");
writer.append(newLine);//向缓冲区写入修改后的字符串
writer.close();//关闭writer后,会将缓冲区的数据写入目标文件
} catch (FileNotFoundException e) {
System.out.println(filename);
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
File temp=new File(homeDir+str+"/");
if(temp.isDirectory()) {
replaceTxtFileContent(homeDir+str+"/",orgStr,targetStr);
}
}
}
}
}
  1. 查看文件大小
1
2
File file=new File(filePath);
long fileSize=file.length();
  1. 等待一段时间后再执行程序
1
2
3
4
5
6
TimeUnit.DAYS.sleep(1);//天
TimeUnit.HOURS.sleep(1);//小时
TimeUnit.MINUTES.sleep(1);//分TimeUnit.SECONDS.sleep(1);//秒
TimeUnit.MILLISECONDS.sleep(1000);//毫秒
TimeUnit.MICROSECONDS.sleep(1000);//微妙
TimeUnit.NANOSECONDS.sleep(1000);//纳秒
  1. 向文本文件中写入数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//写入数据的函数
public void writeByBytes(byte[] bytes) {
File file=new File(Base.root+this.fileAddr);
if(file.exists()==false) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
OutputStream out;
try {
out = new FileOutputStream(file, false);
out.write(bytes);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//调用函数按字节写入字符串
public static void main(String[] args) {
String filePath="xxx/xxx/.../xxx.txt";
File file=new File(filePath);
String content="abc";
file.writeByBytes(content.getBytes("UTF-8"));
}
  1. 动态调用类/函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//创建类MyClassFactory
public class MyClassFactory {
public MyClassFactory(String string) {
try {
//根据给定init文件初始化类
//Init类中Initialization函数为按行读入路径为string的文件
//并将参数放到map中,键为类的名字,值为为一个map
//这个map的键为属性名,值为所读文件中所给的具体值
Init.Initialization(string);
} catch (IOException e) {
e.printStackTrace();
}
}
//动态调用创建对象
public <T>T createInstance(Class<T> clazz) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
//得到类的名字
String className=clazz.getName();
//用泛型新建一个对象
T obj=clazz.newInstance();
//在类map中得到参数map
Map<String,Object> parameter=Init.myClasses.get(className);
//迭代调用setXXX函数赋值
//其中it为参数map的keySet
Iterator<String> it=parameter.keySet().iterator();
while(it.hasNext()) {
//property为类的属性名
String property=it.next();
//value为该属性的具体值
Object value=parameter.get(property);
//methodName为调用函数的名字,这里为setXXX
String methodName="set"+property.substring(0, 1).toUpperCase()+property.substring(1);
//调用函数复制
Method method=obj.getClass().getMethod(methodName, value.getClass());
method.invoke(obj, value);
}
//返回所建的对象
//即为动态调用创建对象
return obj;
}
}
public class Init{
public static Map<String,Map<String,Object>> myClasses=new HashMap();
public static void Initialization(String filename) {
//...
//按行读入文件
//将文件中所给参数存到myClasses中
}
}
  1. 多线程解决问题
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//例如寻找一个大范围内所有的质数然后升序输出
//首先创建PrimeUtil类,类中会调用继承Thread类的GetPrimeNum类线程
public class PrimeUtil {

public long threadStart,threadEnd;

public List<Long> primeList=new ArrayList<>();

public PrimeUtil(long ts, long te) {
this.threadStart=ts;
this.threadEnd=te;
}

public PrimeUtil() {
}

public List<Long> getPrimeList(long start, long end, int threadCount) {
GetPrimeNum threads[]=new GetPrimeNum[threadCount];
//找start到end之间的质数,运用多线程
//使用threadCount个线程分别计算某个区间
for(int i=0;i<threadCount;i++) {
//计算每个区间的起始位置和结束位置
long threadStart=start+i*(end-start)/threadCount;
long threadEnd=start+(i+1)*(end-start)/threadCount;
threads[i]=new GetPrimeNum(threadStart,threadEnd);
//线程开始运行,注意要用start()而不是run()
threads[i].start();
}
//将每个线程的结果合并得到问题的总结果
for (int i = 0; i < threads.length; i++) {
try {
threads[i].join();
List<Long> tmp = threads[i].getList();
primeList.addAll(tmp);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//保险起见,使用Collentions对找到的质数进行排序
Collections.sort(primeList);
return primeList;
}
}
//创建GetPrimeNum类继承Thread
public class GetPrimeNum extends Thread{

public List<Long> tempList=new ArrayList<>();

public GetPrimeNum(long ts,long te) {
this.threadStart=ts;
this.threadEnd=te;
}

public long threadStart,threadEnd;

//将线程需要执行的代码写在run()函数中
public void run() {
for(long i=this.threadStart;i<this.threadEnd;i++) {
if(isPrime(i)) {
tempList.add(i);
}
}
}

public boolean isPrime(long n) {
for(int i=2;i<=Math.sqrt(n);i++) {
if(n%i==0) return false;
}
return true;
}

public List<Long> getList(){
return this.tempList;
}
}
  1. socket编程-服务端和客户端一对一交互
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
//创建MyServer类继承Thread类
public class MyServer extends Thread {
//服务器属性端口号
public int port;
//监听函数
public void startListen(int port) {
this.port = port;
Thread serverListenThread=new Thread(this);
serverListenThread.start();
}
//线程run函数
public void run() {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
//新建ServerSocket
ServerSocket myServer = new ServerSocket(port);
//等待客户端与服务端连接
socket = myServer.accept();
//获得输入输出流
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
String Line = in.readLine();
while (!"bye".equals(Line)) {
out.write(Line + "\r\n");
out.flush();
Line = in.readLine();
}
in.close();
out.close();
socket.close();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
close(in);
close(out);
close(socket);
}
}
public static void close(Closeable inout) {
if (inout != null) {
try {
inout.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//新建Test类进行测试
public class Test {

public static boolean testEcho(BufferedReader in, PrintWriter out, String line) throws IOException {
out.write(line + "\r\n");
out.flush();
String echoline = in.readLine();
if (line.equals(echoline)) {
return true;
} else {
return false;
}
}

public static void main(String[] args) {
// TODO Auto-generated method stub
// 端口号测试的时候随机给
int port = 8088;
// 要求完成MyServer类
new MyServer().startListen(port);
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket("127.0.0.1", port);
out = new java.io.PrintWriter(socket.getOutputStream());
// 获得输入流
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// 随机测试向服务器端输入几句话,要求服务器端原封不动返回
if (testEcho(in, out, "hellow")) {
System.out.println("ok 1");
}
if (testEcho(in, out, "haha")) {
System.out.println("ok 2");
}
// 向服务器端输入bye,断开表示断开连接
out.write("bye" + "\r\n");
out.close();
in.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(in);
close(out);
close(socket);
}
}

public static void close(Closeable inout) {
if (inout != null) {
try {
inout.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}
  1. socket编程-服务端和客户端一对多交互
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
//要求客户端发送一个数到服务端
//服务端将这个数的两倍发送给客户端
//新建MyServer类继承Thread类
//监听函数即startListen()中使用while循环等待与客户端连接
//如果在服务端开始监听后还需要执行startListen后面的代码,则需要使用线程来监听
//否则MyServer无需继承Thread类
public class MyServer extends Thread {
//服务器属性端口号
public String ip;
public int port;
public MyServer(String ip,int port) {
this.ip=ip;
this.port=port;
}
public MyServer() {}
//监听函数
public void startListen() {
Thread serverListenThread=new Thread(this);
serverListenThread.start();
}
//线程run函数
public void run() {
try{
ServerSocket server=new ServerSocket(this.port);
int id=0;
while(true) {
Socket socket=server.accept();
new Thread(new ServerThread(id,socket)).start();
id++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
//新建ServerThread继承MyServer类
public class ServerThread extends MyServer {
public int id;
public Socket socket;
public ServerThread(int id,Socket socket) {
this.id=id;
this.socket=socket;
}
public void run() {
try {
BufferedReader in = null;
BufferedWriter out = null;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String line = in.readLine();
int value=2*Integer.valueOf(line);
out.write(value);
System.out.println(out.toString());
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
//新建Client类
public class Client {
public String name;
public String ip;
public int port;
Socket client = null;
BufferedReader in = null;
BufferedWriter out = null;
public Client(String name,String ip,int port) {
this.name=name;
this.ip=ip;
this.port=port;
}
private void close() {
// TODO Auto-generated method stub
try {
this.in.close();
this.out.close();
this.client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendMessage(String content) {
try {
client = new Socket(ip,port);
out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
out.write(this.name+":"+content);
out.flush();
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println(in.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
}
//新建Test类测试
public class Test {
public static void main(String[] args) {
String ip = "127.0.0.1";
int port = 9090;
MyServer myServer;
try{
myServer=new MyServer(ip,port);
myServer.startListen();
Client A=new Client("A",ip,port);
Client B=new Client("B",ip,port);
Client C=new Client("C",ip,port);
System.out.println("Here");
A.sendMessage("2");
} finally {
}
}
}
  1. 日期与字符串相互转换
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class DateDemo {

public DateDemo() {
}

public static void main(String[] args) {
try {
System.out.println(new java.util.Date());

//日期转换为字符串
String str = dateToStr(new java.util.Date(), "yyyy-MM-dd HH:mm:ss");
System.out.println(str);

//字符串转换为日期
Date date = strToDate(str, "yyyy-MM-dd HH:mm:ss");
System.out.println(date);
//毫秒转换为日期
long curMills=System.currentTimeMillis();
Date date2=new Date(curMills);
System.out.println(date2);

} catch (ParseException e) {
e.printStackTrace();
}
}

public static String dateToStr(java.util.Date date, String pattern) {
SimpleDateFormat df = new SimpleDateFormat(pattern);
return df.format(date);
}

public static Date strToDate(String date, String pattern) throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
java.util.Date outDate = formatter.parse(date);
return outDate;
}

}

Codes

练习源码 备用仓库