如果要把一个对象写入文件 下次还可以取出来 那么这个对象必须实现可序列接口implements Serializable
多线程
静态成员属性属于类 而不属于对象 也就可以理解为一个可变的常量 可以有set get
两种方式:
extends Thread new 类
public void run() {}重写 使用.start
implements Runnable new Thread(类)
public void run() {}重写 使用.start
t2.setPriority(Thread.NORM_PRIORITY);
try {
// 合并,联合:当前调用这行代码的线程(次代码处未main线程)和被.join的线程(此处t)联合。当前调用这行代码的线程会一直阻塞,等到t执行完成后才继续恢复。
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
//////////////////////////////////////////////////////////////////////////////////////////////
try {
synchronized(totaler) {
if(totaler.complete == false) {
totaler.wait();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
public synchronized void receive(int sum) {
total += sum;
curr_count++;
if(curr_count == max_count) {
complete = true;
this.notify();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
网络通信编程:
String ip = "localhost";
int port = 8888;
// 套接字 对象
try {
// 可以与服务器端通信的网络终端对象
Socket socket = new Socket(ip, port);
System.out.println("客户端连接到服务器");
// 创建一个基于socket的输出流写入对象
PrintWriter out = new PrintWriter(socket.getOutputStream());
// 创建一个基于socket的输入流读取对象
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true) {
Scanner input = new Scanner(System.in);
System.out.print("\n请输入任意内容(输入bye,退出):");
String content = input.next();
if(content.equals("bye")) {
break;
}
out.println(content);
out.flush();
System.out.println("客户端发送了数据“" + content + "”");
String data = br.readLine();
System.out.println("客户端从服务器端读到了:" + data);
}
br.close();
out.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器在8888端口号上建立监听");
int count = 0;
while(true) {
System.out.println("\n等待第" + ++count + "客户端连接....");
Socket socket = serverSocket.accept();
HandlerForClient handler = new HandlerForClient(socket);
handler.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
反射:
/* 三种获取Class的方式 */
public static void threeGetClass() {
// 通过 对象.getClass() --> Class
Teacher t = new Teacher();
Class c1 = t.getClass();
// 通过 类名.class --> Class
Class c2 = Teacher.class;
// 通过Class的静态方法 Class.forName("完全类名") --> Class
try {
Class c3 = Class.forName("sample.entity.Teacher");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Constructor c = constructors[i];
// 根据“构造器对象”的newInstance方法,来创建对象
Teacher teacher = (Teacher) c.newInstance();
// 反射类的字段(Field)
Field[] fields = cls.getDeclaredFields();
System.out.print(",修饰符:" + Modifier.toString(f.getModifiers()))
System.out.print(", 类型:" + f.getType().getName());
System.out.println(",值:" + f.get(t)); 必须有值
其实只能用invoke方法
Method[] methods = cls.getDeclaredMethods(); // 获取本类中定义的所有修饰符的方法,不包括父类中定义的
Method[] methods1 = cls.getMethods(); // 获取所有的public的方法,包括父类中定义的。
System.out.println("返回值类型占位符:" + m.getReturnType().getName());
System.out.println("方法的参数的个数:" + m.getParameterCount());
Object returnValue = m.invoke(zl); // 调用类的某个方法对象的invoke方法:在指定的对象上(zl),调用m方法
System.out.println("调用了" + m.getName() + ",返回值为:" + returnValue);
/* 打印任意类型对象的java bean 字段和字段的值 */
public static void printBeanFields(Object obj) {
Class cls = obj.getClass();
Method[] methods = cls.getMethods();
for (Method m : methods) {
String mn = m.getName();
if (mn.startsWith("get")
&& mn.length() > 3
&& !mn.equals("getClass")
&& m.getParameterCount() == 0
&& !m.getReturnType().getName().equals("void")) {
String beanFieldName = mn.substring(3);
beanFieldName = beanFieldName.substring(0, 1).toLowerCase() + beanFieldName.substring(1);
try {
Object returnValue = m.invoke(obj);
System.out.println(beanFieldName + ": " + returnValue);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
XML
// 创建了一个xml文件的读取器对象:reader
SAXReader reader = new SAXReader();
// 使用reader来读取指定的xml文件(school.xml),读取成功后,返回整个文档对象Document:doc
Document doc = reader.read("school.xml");
// 通过doc来获取整个文档中的根元素对象
Element root = doc.getRootElement();
/*
// 获取root元素的子元素对象:Element
Element elemName = root.element("name");
// 获取elemName元素的文本:getTextTrim
String name = elemName.getTextTrim();
System.out.println(name);
*/
// 获取root元素中元素名为name的子元素的文本
System.out.println("学校名:" + root.elementText("name"));
System.out.println("学校地址:" + root.elementText("address"));
// 获取根元素中名为klasses子元素下的所有子元素(klass的元素列表)
List<Element> elemKlassList = root.element("klasses").elements();
System.out.println("学校中共有班级:" + elemKlassList.size() + "个班,详细信息如下:");
for(Element elemKlass : elemKlassList) {
System.out.println("\n\t班级编号:" + elemKlass.attributeValue("id"));
System.out.println("\t班级名称:" + elemKlass.elementText("name"));
System.out.println("\t专业方向:" + elemKlass.elementText("prof"));
System.out.println("\t开班日期:" + elemKlass.elementText("open"));
//如果klasses里面没有klass标签
//那么 System.out.println(elemKlass .getText());
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
文件写入
Document doc = DocumentHelper.createDocument();
Element elemBooks = doc.addElement("books");
Element book1 = elemBooks.addElement("book");
book1.addAttribute("isbn", "B10123719312937812");
book1.addElement("title").addText("三国演义");
Element book1Price = book1.addElement("price");
book1Price.addAttribute("unit", "人民币");
book1Price.addElement("old").addText("¥128.5");
book1Price.addElement("curr").addText("¥82.5");
elemBooks.addElement("book");
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter xmlWriter = null;
try {
xmlWriter = new XMLWriter(new OutputStreamWriter(new FileOutputStream("books.xml"), "UTF-8"), format);
xmlWriter.write(doc);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(xmlWriter != null) {
try {
xmlWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
文件读出另一种方式 没用dom4j
try {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(new FileInputStream("school.xml"), new MyHandler());
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class MyHandler extends DefaultHandler {
// public void startDocument() throws SAXException {
// System.out.println("\n读到文档的开头了!");
// }
@Override
public void setDocumentLocator(Locator locator) {
// TODO Auto-generated method stub
super.setDocumentLocator(locator);
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
System.out.println("\n读到一个元素了:" + qName + ", " + attributes.getLength());
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String content = new String(ch, start, length);
System.out.println("\n读到了内容了:" + content);
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
System.out.println("\n读完一个元素了:" + qName );
}
@Override
public void endDocument() throws SAXException {
System.out.println("\n读到文档的结尾了!");
}
//////////////////////////////////////////////////////////////////////////////////////////////
注解Annotation
Retention(保留)注解说明,这种类型的注解会被保留到那个阶段. 有三个值:
1.RetentionPolicy.SOURCE —— 这种类型的Annotations只在源代码级别保留,编译时就会被忽略
2.RetentionPolicy.CLASS —— 这种类型的Annotations编译时被保留,在class文件中存在,但JVM将会忽略
3.RetentionPolicy.RUNTIME —— 这种类型的Annotations将被JVM保留,所以他们能在运行时被JVM或其他使用反射机制的代码所读取和使用.
1.CONSTRUCTOR:用于描述构造器
2.FIELD:用于描述域
3.LOCAL_VARIABLE:用于描述局部变量
4.METHOD:用于描述方法
5.PACKAGE:用于描述包
6.PARAMETER:用于描述参数
7.TYPE:用于描述类、接口(包括注解类型) 或enum声明
public @interface Column {
String value();
boolean primaryKey() default false;
boolean autoIncrement() default false;
}
@Column(value="BCode", primaryKey=true)
public String getIsbn() {
return isbn;
}
Class<?> cls = Student.class;
Method[] methods = cls.getDeclaredMethods();
for(Method m : methods) {
System.out.println(m.getName() + "方法是否存在MethodAnnotation注解:" + m.isAnnotationPresent(MethodAnnotation.class));
}
//判断类对象上是否存在指定的注解类型
if(cls.isAnnotationPresent(MyAnnotation.class)) {
// 获取类对象上的指定注解对象
MyAnnotation ma = (MyAnnotation) cls.getAnnotation(MyAnnotation.class);
String value = ma.value();
String author = ma.author();
double[] versions = ma.versions();
System.out.println(value);
System.out.println(author);
System.out.println(Arrays.toString(versions));
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
单元测试和Juint
assertEquals(this.level, result);
assertFalse("测试existsLoginId不存在的条件,失败了:测试数据“zhaomin”不存在,期待返回false,但实际结果为true",
userService.existsLoginId("zhaomin"));
assertTrue("测试existsLoginId存在的条件,失败了:测试数据“zhangwuji”存在,期待返回true,但实际结果为false",
userService.existsLoginId("zhangwuji"));
public void setUp() throws Exception 在每个单元方法测试前清空
calculator.clear();
参数化测试。
@RunWith(Parameterized. class )
public class SquareTest {
private static Calculator calculator = new Calculator();
private int param;
private int result;
@Parameters
public static Collection data() {
return Arrays.asList( new Object[][] {
{ 2 , 4 } ,
{ 0 , 0 } ,
{- 3 , 9 } ,
} );
}
// 构造函数,对变量进行初始化
public SquareTest( int param, int result) {
this .param = param;
this .result = result;
}
@Test
public void square() {
calculator.square(param);
assertEquals(result, calculator.getResult());
}
打包测试。
@RunWith(Suite. class )
@Suite.SuiteClasses( {
CalculatorTest. class ,
SquareTest. class
} )
public class AllCalculatorTests {
}
//////////////////////////////////////////////////////////////////////////////////////////////
Mysql高级
drop database if exists test;
create database test;
use test;
create table tbl_klass
(
kid int primary key auto_increment,
kname varchar(20) not null
);
create table tbl_student
(
sid int primary key auto_increment,
sno char(6) not null unique,
sname varchar(20) not null,
sbirthdate date,
sex enum(‘男‘, ‘女‘) not null,
saddr varchar(100) default ‘博为峰学生公寓‘,
sregistTime datetime not null,
skid int not null,
foreign key (skid) references tbl_klass (kid)
);
insert into tbl_klass (kname) values (‘11期‘), (‘12期‘), (‘13期‘);
select * from tbl_klass;
insert into tbl_student values (null, ‘S10015‘, ‘杨玉松‘, ‘1970-9-2‘, ‘女‘, default, now(), 1);
select * from tbl_student;
/* 创建一个视图 */
create view v_students as
select sno, sname, kname from tbl_student left join tbl_klass on skid = kid;
/* 删除一个视图 */
drop view if exists v_students;
函数
select char_length(‘我们love‘);
select *, char_length(sname) ‘姓名字数‘ from tbl_student;
select ‘对方‘ + ‘5‘;
select ‘学号:S10013,姓名:‘
select CONCAT(‘学号:‘, sno, ‘,姓名:‘, sname) ‘学生西宁‘ from tbl_student;
select insert(‘hello,jzp,hi‘,1, 0, ‘dd‘);
select REPLACE(‘我们的AAA主席非常厉害,我爱AAA。‘, ‘AAA‘, ‘****‘)
select left(‘[email protected]‘, locate(‘@‘, ‘[email protected]‘)-1) ‘username‘;
select right(‘[email protected]‘, char_length(‘[email protected]‘) - locate(‘@‘, ‘[email protected]‘) );
select SUBSTRING(‘[email protected]‘, locate(‘@‘, ‘[email protected]‘)+1);
select *, ifnull(saddr, ‘未知住址‘) as address, if(sex = ‘男‘, ‘male‘, ‘female‘) as ‘gender‘ from tbl_student;
select
sname,
sscore,
sdengji,
case
when sscore >= 90 then ‘Good‘
when sscore >= 60 then ‘Normal‘
else ‘Bad‘
end as en,
case sdengji
when ‘优‘ then ‘☆☆☆‘
when ‘中‘ then ‘☆☆‘
else ‘☆‘
end as ‘star‘,
saddr
from tbl_student;
select now();
select left(current_date(),4);
select current_time();
-- 获取当前日期时间(指定日期时间)的时间戳
select unix_timestamp();
select year(now());
select month(now());
select day(now()), dayofmonth(now());
select hour(now());
select minute(now());
select second(now());
select dayofweek(‘1995-5-3‘), weekday(‘1995-5-3‘), dayname(now());
select DAYOFYEAR(now());
select week(now()), WEEKOFYEAR(now());
select * from where year(sellTime) = year(now()) and month(now()) - month(sellTime) = 1
select TIMESTAMPDIFF(year, ‘2016-8-25 8:27:00‘, now());
select DATE_ADD(now(),INTERVAL (-5) minute)