Java中Api知识点总结笔记带案列

博客园 CSND 开源中国 w3school前端网站 一个汉字俩个字节 一个英文一个字节

《Arraylist的用法》

包含了 list.size() list.get() list.add()方法 list.set() list.remove
package ArrayList;

import java.util.ArrayList;

public class Newguanli {

/*public void showNew(){
//1先创建集合对象
ArrayList list=new ArrayList();
//2添加集合元素 长度默认10 // 在集合的末尾
list.add(new New("小猪佩奇开学了吗今天1","彤彤",001));
list.add(new New("小猪佩奇开学了吗今天2","琪琪",002));
list.add(new New("小猪佩奇开学了吗今天3","彤彤",003));
//3获得新闻的个数
System.out.println("获得新闻的个数"+list.size());


}*/


/(第二种使用Arraylist方法)/


//1先创建集合对象
ArrayList list=new ArrayList();
/**
*通过Newguanli无参构造对集合就行添加
*/
public Newguanli(){
//2 构造方法添加集合元素 长度默认10
list.add(new New("小猪佩奇开学了吗今天1","彤彤",001));
list.add(new New("小猪佩奇开学了吗今天2","琪琪",002));
list.add(new New("小猪佩奇开学了吗今天3","彤彤",003));
}
/**
* 通过下标,添加新闻
*/
public void addNew(int index,New news ){
list.add(index, news);
}
/**
* 去测试的话类里写的方法
* Newguanli guanli=new Newguanli();
System.out.println("添加前的新闻");
guanli.showNew();
New news=new Book("小猪佩奇开学了吗今天1","彤彤",001)
guanli.addNew(0,news)
System.out.println("修改后的新闻");
guanli.showNew();
*
*
*
*
*
*
*/


public void showNew(){
//查看集合的第一个方法 使用普通for 有2个
/*//查看新闻的个数
System.out.println("新闻标题\t\t\t\t"+"新闻作者\t\t"+"\t新闻编号");
for (int i = 0; i < list.size(); i++) {
//每循环一次通过get方法提取及集合中的元素
Object obj=list.get(i);
if(obj instanceof New){
New news=(New)obj;
System.out.println(news.getTitle()+"\t\t"+news.getZuozhe()+"\t\t\t"+news.getId());
}
}*/

/*System.out.println("新闻标题\t\t\t\t"+"新闻作者\t\t"+"\t新闻编号");
for (int i = 0; i < list.size(); i++) {
New news=(New)list.get(i);
System.out.println(news.getTitle()+"\t\t"+news.getZuozhe()+"\t\t\t"+news.getId());
}
}*/
///查看集合的第二个方法 增强for
System.out.println("新闻标题\t\t\t\t"+"新闻作者\t\t"+"\t新闻编号");

for (Object obj: list) {
if(obj instanceof New){
New news=(New)obj;
System.out.println(news.getTitle()+"\t\t"+
news.getZuozhe()+"\t\t\t"+news.getId());
}
}
}
/**
* 根据新闻的标号找下标
* @param args
*/
public int getIndexById(int id){
int index=-1;
for (int i = 0; i < list.size(); i++) {
New news=(New)list.get(i);
if(id==news.getId()){
index=i;
break;
}
}
return index;
}

/**
* 根据参数的id 寻找集合中元素匹配的下标
* 修改功能
* @param id
* @param title
*/
public void updateNewtitle(int id,String title){
int index=this.getIndexById(id);
if(index==-1){
System.out.println("没有找到你要修改的新闻");
}else{
New news=(New)list.get(index);
news.setTitle(title);
list.set(index, title);
System.out.println("新闻修改成功");
}
}
/**根据新闻编号删除新闻
* 删除功能
* @param args
*/
public void delNewById(int id){
int index=this.getIndexById(id);
if(index==-1){
System.out.println("没有找到你要修改的新闻");
}else{
//根据下标删除元素 list的方法是list.remove
list.remove(index);
System.out.println("删除成功");
}
}
/**
* 根据对象属性和集合中的地址删除对象
*/
public void DelNew(){
New news=new New("小猪佩奇开学了吗今天1","彤彤",001);
System.out.println(news);//删除对象名字会获得对象的哈希玛值
list.remove(news);
//根据对象名字删除集合中的元素
//(对象的属性和集合中的地址相同才可以删除 跟属性值无关)
}
/**
* 根据对象属性和集合中的地址删除对象
*/
public void DelNew2(){
New news=(New)list.get(0);
list.remove(news);
}

public int getSize() {
return list.size();//返回个数
}

public void clear() {
list.clear();//清0操作
}



public static void main(String[] args) {
Newguanli guanli=new Newguanli();
guanli.showNew();
}

}

 

《一个新的添加方法》
//修改方法
public void xiugai(){
//记录修改的名字
String[]names=new String[3];
//记录修改的腿数
int[] nums=new int[2];
System.out.println("请输入猫名字");
names[0]=input.next();
System.out.println("请输入猫的的腿数");
nums[0]=input.nextInt();
System.out.println("请输入鸭子名字");
names[1]=input.next();
System.out.println("请输入鸭子的腿数");
nums[1]=input.nextInt();
System.out.println("请输入海豚名字");
names[2]=input.next();
animals[0]=new Cat(names[0],nums[0]);
animals[1]=new Duck(names[1],nums[1]);
animals[2]=new Dolphin(names[2]);


《修改集合的方法》
public void updateNewtitle(int id,String title,String zuozhe){
int index=this.getIndexById(id);
if(index==-1){
System.out.println("没有找到你要修改的新闻");
}else{
New news=(New)list.get(index);
news.setTitle(title);
news.setZuozhe(zuozhe);
list.set(index, news);<<<<<<<<<<<<<<<<<注意是news
System.out.println("新闻修改成功");
}
}

---------------------------------------------------------------------------------------------
上面有对集合的增删改查
1查 可以for查看集合的所有对象(get(index)) 也可以查询单个的 通过id 拿到get(index)
2 修改 id是不能修改的 通过id找对象的下标 找到后进行修改 再把用户给的String类型封装在一个对象里
3 增加 add
4 删除 也是通过id找到index list.remove(index);


------------------------------------------------------------------------------------

 

------->《LinkedList 中add添加的顺序 first 和last》


New new2=new New("小猪佩奇开学了吗今天2","彤彤",002);
New new3=new New("小猪佩奇开学了吗今天33333","彤彤",002);
New new4=new New("小猪佩奇","彤彤",002);
LinkedList list= new LinkedList();
list.add(new1);
list.add(new2);
list.add(new3);
list.addFirst(new4);
list.addLast(new1);
list.add(new3);
for (Object obj : list) {
New news=(New)obj;
System.out.println(news.getTitle()+"\t\t"+
news.getZuozhe()+"\t\t\t"+news.getId());

}
输出的排列顺序
小猪 彤彤 1
小猪佩奇开学了吗今天2 彤彤 2
小猪佩奇开学了吗今天33333 彤彤 2
小猪 彤彤 1
小猪佩奇开学了吗今天33333 彤彤 2


《引用变量new对象的注意事项》

//1 创建集合对象
//2set的特点 是 唯一 无序的
Set set=new HashSet();
String s1=new String("java");//String也是引用变量可以new
String s2=s1;
String s3=new String("JAVA");
String s4=new String("java");
//添加元素
set.add(s1);//-------》如果放进去的是数字那数字就变成了一个引用类型变量了
set.add(s2);
set.add(s3);
set.add(s4);
System.out.println("元素个数"+set.size());
------------>《collections的用法》
package cn.collcetions;
import java.util.ArrayList;
import java.util.Collections;
public class Tsetcoollections {

public static void main(String[] args) {
System.out.println("******************基本数据类型*************************");
ArrayList<Integer> list=new ArrayList<Integer>();
list.add(1);
list.add(1);
list.add(2);
list.add(3);
list.add(4);
//对集合进行排序 把集合转换成数组的方法是 list.toArray();
Collections.sort(list);
for (Integer inte : list) {
System.out.println(inte);
}
System.out.println("*********************引用数据类型***********************************");
ArrayList<Student>list1=new ArrayList<Student>();
list1.add(new Student("a",5,"男"));
list1.add(new Student("b",10,"男"));
list1.add(new Student("c",15,"男"));
//使用Collections之前要把比较的类继承这个Comparable<Student>接口
//重写这个compareTo方法
Collections.sort(list);
for (Student stud : list1) {
System.out.println(stud.getName()+stud.getSex()+stud.getAge());
}
}
}
//使用Collections之前要把比较的类继承这个Comparable<Student>借口
//重写这个compareTo方法做出比较规则

----------->《泛型的 知识》
将对象的类型作为参数 指定到其他的类或者方法上从而保证了类型转换的安全性
* 和稳定性 这就是泛型
* 他的本质就是参数化类型
* JDK1.5中改写了集合框架中的所有接口和类 增加了泛型的支持也就是泛型集合
* 泛型集合只是泛型引的一种应用
* 泛型集合中必须放的是引用基本数据类型
* 如果想放入基本数据类型 必须使用他们的包装类
* int---》 Intger double----->Double
int---》 Intger double----->Double使用类型


《Map里的一些用法》


package map;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Test1 {
public static void main(String[] args) {
Map map=new HashMap();
map.put("CN", "中华人");
map.put("US", "美国人");
//通过Map集合的values的方法获取所有的Value集合(类型是collection)
//遍历collection集合
//第一个方法
Collection coll=map.values();
for (Object obje : coll) {
System.out.println(obje);
}
/*
for (Object obj: map.values() ) {
System.out.println(obj);
}
*/
System.out.println("-------------以下是第个2方法获得键值-------------");
//第二个方法
Set set=map.keySet();
for (Object obj : set) {
System.out.println(obj);
}

/*for (Object key : map.keySet()) {
System.out.println(key);
}*/
System.out.println("--------------------------");
//第三个方法
/*Iterator it=map.values().iterator();
while(it.hasNext()){
Object obj=it.next();
System.out.println(obj);
}*/
Iterator it =map.keySet().iterator();
while(it.hasNext()){
Object obj=it.next();
System.out.println(obj);
}

//通过get方法 输入key获得一个value
System.out.println("--------------------------");
String key="US";
if(map.containsKey(key)){
System.out.println(map.get(key));
}else{
System.out.println("你属于的key值和这个建值没有关系");
}
System.out.println("-----------视频上的---------------");
//1分别获得键集
//2分别获得值集------------>打印出去的是带中括号的那种;
//3一起获得键值对集
System.out.println(map.keySet());
System.out.println(map.values());
System.out.println(map);
System.out.println("-----------视频上的---------------");
//(1)先获得key 在根据获得的key拿到value

Set keys=map.keySet();
//可以用增强的for拿到
for (Object obj : keys) {
String jian=(String)obj;
String value=(String)map.get(jian);//get可以得到键
System.out.println(jian+"对应"+value);
}
//也可以用迭代器拿到
System.out.println("------------------------");
Iterator iter=map.keySet().iterator();
while(iter.hasNext()){
String jian=(String)iter.next();
String value=(String)map.get(jian);
System.out.println(jian+"对应"+value);
}
System.out.println("------------------------");
//(2)先获得键值对 在对每个键值对获得键集和值集 用的是entrySet()方法
Set ms=map.entrySet();//<-----------用到了entrySet
for (Object obj : ms) {
Map.Entry me=(Map.Entry)obj;//<-------用到了Map.Entry 它是一个类型 键值对的类型
Object key1=me.getKey();
Object value1=me.getValue();
System.out.println((String)key1+"是代表"+(String)value1);
}
}

}
《随机打印五注彩票的代码》

package cn.caipiao;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class NumberUtil {
public ArrayList<Integer> getReds() {
// 红色球的集合 set保证了她的不唯一 不重复
HashSet<Integer> set = new HashSet<Integer>();
// 产生6个1-33的随机数字
do {
int red = (int) (Math.random() * 33) + 1;// 红色球1~33
set.add(red);
} while (set.size() != 6);// 当红球够6个的时候跳出循环
//再把红球放进list保证了打印出来的红球有顺序 而且不重复
ArrayList<Integer> reds = new ArrayList<Integer>();

for (Integer num : set){
reds.add(num);
}
Collections.sort(reds);

return reds;
}

public int getBlue(){
return (int)(Math.random()*16)+1;
}

public String print(){
ArrayList<Integer> reds=this.getReds();
int blue=this.getBlue();
String str="";
for (Integer red : reds) {
str+=red+" ";
}

str+=" + "+blue;

return str;
}

public static void main(String[] args) {
NumberUtil util=new NumberUtil();

for (int i = 0; i < 5; i++) {
System.out.println(util.print());
}

}

}
/ 红色球的集合 set保证了她的不唯一 不重复
//再把红球放进list保证了打印出来的红球有顺序 而且不重复 有顺序后可以进行排序

《枚举的知识点 》
例子代码

 

//--------1 自定义赋值------------
//Student stu=new Student();
//stu.setSex(Genders.男); //这是通过sex访问器赋值 赋值的时候用枚举点出来东西赋值
//System.out.println("性别为"+stu.getSex());


//----------2 根据用户输入的值 进行赋值 第一种 容易出错理解就行----------
//Student stu=new Student();
//Scanner input=new Scanner(System.in);
//System.out.print("输入性别");
//String sex=input.next();
//stu.setSex(Genders.valueOf(sex));
//如果set的值没有定义在枚举中 将引发异常IllegalArgumentException
//System.out.println("性别为"+stu.getSex());

//----------2 根据用户输入的值 进行赋值 第2种----------
Scanner input=new Scanner(System.in);
System.out.print("输入性别");
String sex=input.next();
Student stu=new Student();
if("男".equals(sex)|| "女".equals(sex)){
//将String转换成枚举类型
stu.setSex(Genders.valueOf(Genders.class, sex));
}else{
stu.setSex(Genders.女);
}
System.out.println("性别为"+stu.getSex());
1 将枚举类型作为属性的类型 列如 private Genders sex;
2 如何将String类型转换成枚举的类型 用到的是valeueof
3 --------1 自定义赋值------------
----------2 根据用户输入的值 进行赋值 ----------

《总和》
ArrayList<Student> list1=new ArrayList<Student>();
list1.add(new Student("小小",18,"女"));
list1.add(new Student("大大",15,"女"));
ArrayList<Student> list2=new ArrayList<Student>();
list2.add(new Student("长城",19,"男"));
list2.add(new Student("小成",13,"男"));

Map<String, ArrayList<Student>>map=new HashMap<String, ArrayList<Student>>();
map.put("三年级1班", list1 );
map.put("三年级2班", list2);
Scanner input=new Scanner(System.in);
System.out.println("请输入班级");
String key=input.next();
System.out.println("--------->");
if(map.containsKey(key)){
ArrayList<Student> list= map.get(key);
for (Student stu : list) {
System.out.println(stu.getName()+stu.getAge()+stu.getSex());
}
}else{
System.out.println("你输入的班级不存在");
}

 


《包装的知识点》
Long 包装类常量 存储空间是-128到127之间的值维护在一个常量池中 引用的是同一个对象

1 所有包装类都可将与之对应的基本数据类型作为参数,来构造它们的实例
Integer num0=new Integer(1);
2 除Character类外,其他包装类可将一个字符串作为参数构造它们的实例
Double d=new Double("0.5");
3 当Number包装类构造方法参数为String类型时,字符串不能为null,
且该字符串必须可解析为相应的基本数据类型的数据,
否则编译通过,运行时NumberFormatException异常
Integer num=new Integer("abc");---这是错误的
4 Boolean类构造方法参数为String类型时,
若该字符串内容为true(不考虑大小写),
则该Boolean对象表示true,否则表示false
Boolean b=new Boolean("True");

5 转换时 如果超过对应类型的取值范围 则溢出

基本数据向包装类转换---------------
Integer num=new Integer(100000000);
包装类向基本的转换----------------
num.intValue();
System.out.println(num);
转换时 如果超过对应类型的取值范围 则溢出
System.out.println(num.shortValue());
因为short的最大值和最小值是这样
System.out.println("short的最大值"+Short.MAX_VALUE);
System.out.println("short的最大值"+Short.MIN_VALUE);
6 把字符串转换为相应的基本数据类型数据
如果不能转换成功,引发NumberFormatException


7
JDK1.5后,允许基本数据类型和包装类型进行混合数学运算
包装类并不是用来取代基本数据类型的
在基本数据类型需要用对象表示时使用
//基本数据——》包装装换 也可以用valueof
Integer num0=new Integer(1);
Integer num4=new Integer("1");
Integer.valueOf(11);
//字符串--》包装的
Integer.valueOf("2");

//包装----》基本数据 用**value()方法
int b=num0.intValue();

//包装对象表示的
//基本类型数据--字符串 tostring
String str=Integer.toString(12);
//基本类型数据--字符串
int num2=3;
String str1=num2+"";
//字符串--》基本数 用paise**()方法 Character除外
int num3=Integer.parseInt("6");


//允许基本数据类型和包装类型进行混合数学运算
//包装类并不是用来取代基本数据类型的
//在基本数据类型需要用对象表示时使用
int num5=6;
Double num6= new Double(2.0);
double sum=6+num6;


《math的一些用法》
System.out.println("圆周率:"+Math.PI);
System.out.println("E:"+Math.E);

System.out.println("求绝对值:"+Math.abs(-2));
System.out.println("立方根:"+Math.cbrt(9));

System.out.println("返回比参数大的最小整数"+Math.ceil(25.6));

System.out.println(Math.exp(3));

System.out.println("返回比参数小的最大整数"+Math.floor(25.6));

System.out.println(Math.max(2.5, 5.2));

System.out.println(Math.min(2.5, 5.2));

System.out.println(Math.pow(2,3));

System.out.println(Math.round(25.1));

System.out.println(Math.sqrt(4));
        《random的用法》

1先创建对象
Random random=new Random()
random.nextint(10)随机生成0-9之内的数字

//如果用同样一个种子来初始化两个随机数对象
//然后每个对象调用相同的方法,那么得到的随机数也是相同的
Random rand=new Random(100);
Random rand1=new Random(100);

代码列子
String[] strs={"a","b","c","d","e",};
Random rand=new Random();
for (int i = 0; i < 4; i++) {
int num = rand.nextInt(5);
System.out.print(strs[num]);
}
把随机生成的数字--->当做数组的下标随机生成

 

 

2 //如果new出来对象的种子相同 则产生的随机数也是相同的
Random random1=new Random(10);
Random random2=new Random(10);
Random random3=random1;
//但是random3产生的随机数和random1是一样的

 

《String的方法和用法》


String 重写了equale()方法变成了比较字符串的内容 ==比较的是俩个字符串是否是同一对象(new出来才算又有一个对象)
String在new对象的时候 会把new出来的对象先放在字符串池子里面 在放堆里一个 总共2个

1 String 的equals 和== 方法区别

equals比较的是内容
== 比较的是俩个字符串是否是同一对象
new可以产生对象 input.next()也可以产生
---------------第一种比法-------
String str2="hhh";
String str3="hhh";
if(str2.equals(str3)){
System.out.println("11111");
}else{
System.out.println("22222");
}
if(str2==str3){
System.out.println("11111");
}else{
System.out.println("22222");
}//结果输入俩个11111
---------------第2种比法-------
String str4="hhh";
String str5=new String("hhh");
//input.next()也可以产生
if(str4.equals(str5)){
System.out.println("666");
}else{
System.out.println("777");
}

if(str4==str5){
System.out.println("666");
}else{
System.out.println("777");
}
----------------------------------结果是 老师是坑我的
String str1="Keng";
String str2="Keng";
if(str1==str2){
System.out.println("老师是坑我的");
}else{
System.out.println("老师真坑");
}

2 String 的length()方法
返回字符串中的字符个数

3 String 的equalsIgnoreCase()方法是比较俩个对象不区分大小写
列如
String sss=input.next();
String str=input.next();
if(sss.equalsIgnoreCase(str)){
System.out.println("不区分大小的");
}

3() String的toUpperCase() 方法是将此 String 中的所有字符都转换为大写。
String的toLowerCase() 方法是将此 String 中的所有字符都转换为大写。

String str="abc";

String strs=str.toUpperCase();-----》返回的是一个新大写的一定要用变量接受

System.out.println(strs);


/*if(code.equalsIgnoreCase(inputCode)){
System.out.println("验证通过");
}else{
System.out.println("验证失败");
}*/

/*if(code.toUpperCase().equals(inputCode.toUpperCase())){
System.out.println("验证通过");
}else{
System.out.println("验证失败");
}*/

if(code.toLowerCase().equals(inputCode.toLowerCase())){
System.out.println("验证通过");
}else{
System.out.println("验证失败");
}


4 String的getBytes()方法是 获得字节数组 获得是字节的空间
String str="hello";
byte[]bytes=str.getBytes();
for (byte b : bytes) {
System.out.println(b);
}
String num=new String(bytes);
System.out.println(num);
4 String的split()方法是字符串的分解方法 获得字节数 但是要带有特定的格式进行分解
列如
-----------------------第一种带有特殊字符的------------------------
String words="长亭外 古道边 111 222 333 ";
String[] strs=new String[10];
strs = words.split(" ");----》***调用方法后记得放进数组
System.out.println("分解后");
for (String string : strs) {
System.out.println(string);
}
-----------------------用户输入一个字符 查找字符中某一个字符出现的次数------------------------
Scanner input=new Scanner(System.in);
int count=0;
System.out.println("请输入一个字符串");
String str=input.next();//长亭外古道边111222333
System.out.println("请输入你想要的字符串");
String want=input.next();
String[]strs=new String[str.length()];//创建一个长度是 用户输入的字符长度 的数组
for (int i = 0; i < strs.length; i++) {
strs[i]=str.substring(i, i+1);//先截取 截取后在放进strs这个数组中
if(strs[i].equals(want)){
count++;
}
}
System.out.println(want+"在"+str+"出现的次数是"+count);

5 String的 concat(String str)方法是将指定字符串连接到此字符串的结尾

String str="我喜欢";
------------》 str=str.concat("黑鹿晗");(一定要用变量接受下不然加不上)
System.out.println(str);

6 String的str.trim()方法是去掉首尾的空格中间去不掉
列如
String str=" 鹿晗,我对不起你,我要娶你 ";
System.out.println("字符串的长度: "+str.length());
System.out.println("去掉空格的长度: "+str.trim().length());
有这样的写法 str.tram.length();返回的是一个新的对象可以点出来东西

7 String的indexOf()方法 lastIndexOf()方法 substring()方法综合运用
String str=" 鹿晗,我对不起你,我要娶你 ";
int index=str.indexOf("我");
int index2=str.indexOf("你");
System.out.println("截取的字符串 "+str.substring(index+1));
System.out.println("截取的字符串 "+str.substring(index+1, index2));
截取的包含第一个 截取的不包含最后一个
8 总和应用
boolean flag=false;
boolean flag1=false;
//文件名必须在有点 切点的后面必须是java 而且要放在最后
System.out.println("----欢迎进入作业提交系统---------");
Scanner input=new Scanner(System.in);
System.out.print("请输入文件名");
String name=input.next();
System.out.print("请输入email名字");
String ee=input.next();
int index=name.indexOf(".");
if(index!=0&&index!=-1&&name.substring(index+1,name.length()).equals("java")){
flag=true;
}else{
System.out.println("文件名有错");
}

//1355022178@qq.com
//ssss.java
boolean flag=false;

System.out.print("请输入Java文件名:");
String f=input.next();
int index=f.indexOf(".");
if(index!=-1&&index!=0&&f.substring(index+1, f.length()).equals("java")){
System.out.println("请输入邮箱");
String e=input.next();
if(e.indexOf("@")!=-1&&e.indexOf(".")>e.indexOf("@")){
flag=true;
if(flag){
System.out.println("作业完成");
}else{
System.out.println("作业格式不对");
}
}else{
System.out.println("邮箱没用");
}
}else{
System.out.println("文件名字无效");
}



《UUID的一些用法》

UUID 格式 xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
(8-4-4-4-12)随机产生这样格式的 代码 包括数字和字母
UUID.randomUUID()返回的是一个对象可以点出来tostring
String str= UUID.randomUUID().toString();
System.out.println(str);

9 在java中添加"" 方法列如System.out.println("\""+want+"\"");给want加双的

 

10 String的charAt(int index)方法是获得 index 位置的char字节数


代码列子 要求用户输入的字符全部是英文

int num='a';
System.out.println(num);
//要求输入的全是英文
//char 可以和数字比较 (和他对应的阿斯克玛值比较但是要先分解字符串才可以比较)
//a-z对应97-122
//A-Z对应65-90
Scanner input=new Scanner(System.in);
System.out.println("请输入一个字符串");
String str=input.next();
boolean flag=false;
for (int i = 0; i < str.length(); i++) {
char zi=str.charAt(i);
if((zi>=97&&zi<=122)||(zi>=65&&zi<=90)){
flag=true;
}else{
flag=false;
break;
}
}
if(flag){
System.out.println("你输入的是"+str);
}else{
System.out.println("格式错误");
}
11 String的正则表达式 matches(String regex) 告知此字符串是否匹配给定的正则表达式。
-----要求输入全部是数字
System.out.println("请输入");
String num=input.next();
String regex="\\d+";
if(num.matches(regex)){
System.out.println(true);
}else{
System.out.println(false);
代表纯数字 }
\\d==[0-9] 用户只能输入一个
\\d+=[0-9]+ 可以多次输入
\\d{4} 恰好4代表格式0000-9999

{次数}

纯英文
[a-zA-Z] 只能输入一个 a 到 z 或 A 到 Z
[a-d[m-p]] 只能输入一个 a 到 d 或 m 到 p
[a-zA-Z]{6,16} 至少 6 次,但是不超过 16 次
[a-zA-Z_0-9]==\\w 代表可以输入单词字符 字母数字下划线
[a-zA-z]\\w{5,17} 6~18个字符, 字母开头 可使用字母、数字、下划线,

12 String的replace()方法 是替换的作用 用“-”代替“**”
String str="111-222-333";
str=str.replace("-", "**");
System.out.println(str);
13 String的split()方法是拆分 返回的是一个String类的数组
String str="长庭院 1111 2222 333 444";
String[] strs=str.split(" ");
for (String string : strs) {
System.out.println(string);
}
14 俩个有参数的构造数组 类型是byte
String(byte[] bytes)
通过使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String。
String(byte[] bytes, int offset, int length, Charset charset)
通过使用指定的 charset 解码指定的 byte 子数组,构造一个新的 String。
15 String 的endswith(“.txt”)指的是 测试此字符串是否以指定的后缀结束
startsWith(String prefix) 测试此字符串是否以指定的前缀开始


《StringBuffer 》

StringBuffer 是可变的 String是不可变得 经常改变内容的字符串要用StringBuffer
1 //String-->StringBuffer
StringBuffer s1=new StringBuffer("hello"); 先创建对象直接在构造方法添加
//StringBuffer-->String 用到了tostring()方法
String s2=s1.toString();
2 append()方法是在原来的字符串后面添加 改变了原字符串 String没有改变自身
StringBuffer s1=new StringBuffer("hello");
s1.append("adddddd");
System.out.println(s1);
3 insert()方法 在这指定位置添加
1 s1.insert(1, "0");
System.out.println(s1);

2 Scanner input =new Scanner(System.in);
System.out.println("请输入一串数字");
String num=input.next();
StringBuffer snum=new StringBuffer(num);
for (int i = snum.length()-3; i > 0; i=i-3) {
snum.insert(i, ",");
}
System.out.println(snum);


《Date 》在util包中 SimpleDateFormat(位于java.text包中) —— (简单的日期格式化)

"yyyy年 MM月 dd日 HH:mm:ss"

1 俩个放在一起变成我们想要的时间格式
Date date=new Date();
System.out.println(date);//当前日期
//格式化日期 变成我们想要的
String geshi="yyyy年MM月dd日 HH:mm:ss"自己定制的时间格式
SimpleDateFormat s1=new SimpleDateFormat(geshi);
String xinshijian1=s1.format(date);返回一个新的String类的
System.out.println(xinshijian1);
2 Calendar (位于java.lang包)这个类也是显示时间和日期的
Calendar t = Calendar.getInstance();
System.out.println(t.get(Calendar.YEAR)+"-"+
(t.get(Calendar.MONTH)+1)+"-"+t.get(Calendar.DAY_OF_MONTH));

3 System.currentTimeMillis()方法
long start=System.currentTimeMillis();
//测试代码
long sum=0;
for (long i = 0; i < 1000000000L; i++) {
sum=sum+i;
}
long end=System.currentTimeMillis();
System.out.println("测试时间 "+(end-start)+"毫秒");

4 SimpleDateFormat有个方法是prise() 将时间格式的字符串转换成(String)转换成Date

Scanner input=new Scanner(System.in);
System.out.println("请输入出生日期");
String chusheng=input.next();
//可以通过
try {
SimpleDateFormat sb=new SimpleDateFormat("yyyy-MM-dd");
Date date=sb.parse(chusheng);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}

------------------《输入和输出 流》-----------------------------------
持久化:程序中的数据在瞬时状态和持久状态转换的过程

将瞬时状态的数据放入 内存中
持久状态的数据放入(存储介质) 文件 二进制流 xml文档 数据库

 


1创建目录
给出文件或者目录的路径
String pathname="F:\\io";
创建文件对象
File f=new File(pathname);
//判断文件或者目录是否存在
if(!f.exists()){
//创建目录
if(f.mkdir()){
System.out.println("创建成功");
}
}


2创建文件
给出文件的路径
String pathname="F:\\io\\1.text\\111.tex";
File f=new File(pathname);
//判断文件或者目录是否存在
if(!f.exists()){
//创建文件
if(f.createNewFile()){
System.out.println("创建成功");
}
}
创建文件的时候 你给出io这个目录 f盘里必须有这个目录才可以创建去创建

3 删除

//给出文件或者目录的路径
String pathname="F:\\io";
//创建文件对象
File f=new File(pathname);
//判断文件或者目录是否存在
if(f.exists()){
if(f.delete()){
System.out.println("删除成功");
}
}
注意的是: 如果目录里面有文件 目录就删除不了 只能删除空文件夹

4 要求创建这样路径的文件String pathname="E:\\io\\1\\1.txt";
String pathname="E:\\io\\1\\1.tet";
File f=new File(pathname);
if(!f.exists()){
if(f.createNewFile()){
System.out.println("创建好");
}
}else{
System.out.println("文件的长度是: "+f.length());
System.out.println("文件的名字 "+f.getName());
System.out.println("文件的相对路径 "+f.getPath());
System.out.println("文件的绝对路径 "+f.getAbsolutePath());
System.out.println("文件是否可以写入内容 "+f.canWrite());
f. list() 列如 (String[] filenames=f.list)
返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中的文件和目录。
}


创建文件只能对他的属性进行操作 如果想输入和输出 读和写就要借助流


-------------------------《输入流》-------------------
输入流的步骤:
1指出文件或目录的路径
第一步:创建文件字节输入流对象
第二步:读取文件的内容,放入字节数组中,构造一个新的 String
第三步:关闭流

 


1 ---------------英文的字节 用的是read()循环一下
文件或目录的路径
String pathname="E:\\io\\1\\1.tet";
FileInputStream fs=null;
int date;
try {
// 创建文件字节输入流对象
fs=new FileInputStream(pathname);
//读取文件内容 用的是read()方法循环读出来
int date;
while((date=fs.read())!=-1){
System.out.println((char)date);
}
} catch (IOException e) {
e.printStackTrace();
fs.close();
}
2---------以String的形式输入(读)出文件的所有内容 文件不是太大的
String pathname="E:\\io\\1\\1.tet"; //文件或目录的路径
FileInputStream fs=new FileInputStream(pathname); //第一步:创建文件字节输入流对象
byte[]bytes=new byte[fs.available()]; // 定义一个字节数组(数组的长度是文件字节大小)
fs.read(bytes); //第二步:读取文件的内容,放入字节数组中
String str=new String(bytes);//构造一个新的String 使用它的有参构造
System.out.println(str);
3--------------大的文件分段截取的代码 用到时 read(bytes 0 intlen)-------------
package cn.kgc.fileinputstream;
import java.io.FileInputStream;
import java.io.IOException;
public class Test3 {
public static void main(String[] args) {
// 文件或目录的路径
String fileName = "E:\\io\\1\\2.txt";
FileInputStream fis = null;
try {
// 第一步:创建文件字节输入流对象
fis = new FileInputStream(fileName);
// 定义一个字节数组(缓冲数组)
byte[] bytes = new byte[1024];
if(fis.available()<1024){
bytes=new byte[fis.available()];
fis.read(bytes);
String str = new String(bytes);
System.out.println("文件内容:" + str);
}else{
int len=fis.read(bytes,0,bytes.length);
while(len !=-1){
// 构造一个新的 String
String str = new String(bytes,0,len);
System.out.println("文件内容:" + str);
len=fis.read(bytes,0,bytes.length);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 第三步:关闭流
if(fis!=null){
fis.close();
}

} catch (IOException e) {
e.printStackTrace();
}
}
}
}
--------------《字节输出流》------------
**注意 FileOutPutStream fos=new FileOutPutStram(String地址 true)
加上这个true是在这个文件里的内容后面追加 不会把文件里面有的东西覆盖掉


1 把所有String类型的写在文件中
String pathname="E:\\io\\1\\4.txt";//指定位置
FileOutputStream f=null;
try {
f=new FileOutputStream(pathname);//创建输出流的对象
// 如果目录存在,文件不存在,创建空文件
//写入数据
String str="好好学习,天天向上";
byte[] bytes=str.getBytes();//放进字节数组中
f.write(bytes);
f.flush();//刷新此输出流并强制写出所有缓冲的输出字节
System.out.println("书写成功");
} catch (IOException e) {

e.printStackTrace();
}finally{
try {
if(f!=null){
f.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

此处步骤
// 第一步:创建文件字节输出流对象
// 第二步:写入数据
用到了 str.getBytes()方法

中文编码格式GBK 有中文英文数字的编码格式 UTF-8
文件复制使用 字节流
文件读取 bufferreader 按行读取的 readline()


-------------------《字符输入流》------------------------


1 使用read()方法进行读
String path="D:\\1\\1.txt"; //指定位置
try {
FileReader fr=new FileReader(path); // 创建字符输入流
int len;
while((len=fr.read())!=-1){
System.out.println((char)len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
2 使用字节数组进行读取的话
try {
FileReader fr=new FileReader(path); //创建字符流对象
char[] buffer=new char[1024]; 创建字符数组
int len; //可以读到的个数
while((len=fr.read(buffer))!=-1){
String str=new String(buffer,0,len);
System.out.println(str);
}
3使用Bufferedreader带有缓冲区的字符流
try {
String fileName = "D:\\250\\1.txt";
// 带缓冲区的字符输入流
BufferedReader reader = new BufferedReader(new FileReader(fileName));
// 逐行读取文件的内容
String str = null;
while ((str = reader.readLine()) != null) {
System.out.println(str);
}
// 关闭流
reader.close();
注意的是
FileReader fr=new FileReader(path); BufferedReader br=new BufferedReader(fr)
===BufferedReader br=new BufferedReader(new FileReader(path))

//BufferedReader reader1=new BufferedReader(
// new InputStreamReader(new FileInputStream(fileName)));

4使用BufferReader 带有自定转码编译器的 格式 字符流 防止中文乱码的代码

try {
InputStreamReader isr=new InputStreamReader(new FileInputStream(fileName), "UTF-8");第一步
BufferedReader br=new BufferedReader(isr); 第二部
//逐条进行读取
String str=null;
while((br.readLine())!=null){
System.out.println(str);
}
// 关闭流
br.close();
--------------------《字符输出流的》----------------------
1-------带有缓冲区的字符输出流
String pathname="D:1.tex";
try {
FileWriter fw=new FileWriter(pathname);
BufferedWriter bw=new BufferedWriter(fw);
//BufferWriter bw=new BufferedWriter(new FileWriter(pathname))
//写入数据
bw.write("好困啊");
bw.newLine();
bw.append("测试");
bw.append('a');
bw.flush();
bw.close();
System.out.println("写入成功");
} catch (IOException e) {
e.printStackTrace();
}

==============《总和练习字符输出流输入流》===============
/*String fileName = "D:\\250\\pet.template";
String saveFileName = "D:\\290\\pet.txt";
try {
FileReader fr=new FileReader(saveFileName);
BufferedReader br=new BufferedReader(fr);
StringBuffer sb=new StringBuffer();
String str=null;
while((str=br.readLine())!=null){
sb.append(str);
}
fr.close();
br.close();
System.out.println(sb);
String newstr=sb.toString().replace("{name}", "欧欧")
.replace("{type}", "拉布拉多犬").replace("{master}", "张三");
FileWriter fw=new FileWriter(fileName);
BufferedWriter bw=new BufferedWriter(fw);
bw.write(newstr);
---------------------------------------------------------------------------------
try {
BufferedReader bf=new BufferedReader(new FileReader("E:\\123\\book.txt"));
BufferedWriter bw=new BufferedWriter(new FileWriter("E:\\123\\books.txt",true));
String str=null;
while((str=bf.readLine())!=null){
System.out.println("替换前"+str);
String sss=str.replace("{name}", "{ssssssss}");
bw.newLine();
bw.write(sss);
System.out.println("替换后"+sss);
}
bw.flush();
bw.close();
bf.close();
System.out.println("ok ");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
==================《总结关系》==================================================
1 file是文件或者目录类 可以创建 删除 在java.io包中
构造方法 File(String parhname)
方法 boolean exists()判断文件是否存在 getname()获得文件名字 boolean delete()是否删除成功 getAbsolutePath()获得绝对路径 geipath()获得相对路径
Boolean isDirectory 是否是目录 Boolean mkdir()是否创建目录 boolean creatnewfile()是否创造一个新的文件
2 字节输入流
inputSteram 父类 常用子类 FileinputSteram读、输入文件
构造方法new FileinputStream(String pathname)

FileinputSteram常用方法
read() read(byte[]b) read(byte[]b 0 len) 都是读 有的带数组 close() 关闭 available()估计剩余字节数

3 字节输出流
outputStream 父类 常用子类 FileoutputStream 写、输出文件
构造方法new FileoutputStream(String pathname)
new FileOutPutStram(String地址 true)不会把文件里面有的东西覆盖掉

FileoutputSteram常用方法
write()write(byte[])write(byte[] o len)都是写 有的带有数组 close() 关闭

4 字符输入流
父类reader 子类 BufferedReader 子类InputStreamReader 孙子FileReader类
构造方法 FileReader(String path)

构造方法 inputSteramReader(String path)inputSteramReader(String path “UTF-8”)和缓冲区buffered一起用
构造方法 BufferedWriter bw=new BufferedWriter(fw);
BufferWriter bw=new BufferedWriter(new FileWriter(pathname))
缓冲区的方法close() readLine()
5 字符输出流
BufferedWriter
缓冲区的方法close() writerLine() flush() newLine()

 

========================《二进制文件的读写》========================
DateinputSteram
DateoutputSteram
===========================《序列化》==============================


objectoutputSteram 序列化 writerobject(object)----------》 写
objectinputSteram 反序列化 reandobject()----》类型转换 读

序列化对象就是把对象写进文件
java对象--(序列化)---》流
java对象《----(反序列化)---流


序列化
// 序列化操作
String fileName = "D:\\250\\wukong.bin";
File file = new File(fileName);
if (file.exists()) {
file.delete();
}
// 创建对象输出流
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream(fileName));
VideoService service = new VideoService();
// 执行序列化操作
os.writeObject(service.getMap());
// 关闭流
os.close();
反序列化
// 反序列化操作
String fileName = "D:\\250\\wukong.bin";
File file = new File(fileName);
if (file.exists()) {
// 对象输入流
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream(fileName));
// 执行反序列化操作
Object obj = ois.readObject();
if (obj instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, VideoRecord> map = (Map<String, VideoRecord>) obj;

for (VideoRecord vr : map.values()) {
System.out.println(vr.getName() + " " + vr.getDate());
}
}

如果不想序列化对象的某个属性加 transient
常见异常
notseriallizableException 类没有实现Seriallizable接口 不可被序列化


==========================《反射》=========================================
含义
程序在运行状态中,动态获取信息以及动态调用对象方法的功能。
运行时动态生成对象实例
运行期间调用方法
运行时更改属性

特点
在编译时不确定哪个类被加载,而在程序运行时才加载、探知、使用
Class类—可获取类和类的成员信息 (反射的起源入口)
Field类—可访问类的属性
Method类—可调用类的方法
Constructor类—可调用类的构造方法

1.导入java.lang.reflect.*
2.获得需要操作的类的Java.lang.Class对象
3.调用Class的方法获取Field、Method等对象
4.使用反射API进行操作 (设置属性﹑调用方法)
Class类存 放类的结构信息 类名 父类﹑接口 方法﹑构造方法﹑属性 注释

获得class对象方式
//方式1:对象.getClass()
Student stu=new Student()
Class al=stu.getclass();

//方式2:类.class
al=Student.class;
al=String.class;

//方式3:Class.forName()
cl=Class.forName("java.lang.String");
cl=Class.forName("java.lang.Date");
每个类都有自己的Class 对象
反射1 String className = "cn.kgc.ref.VideoRecord";
try {
Class cls = Class.forName(className);
//创建对象
VideoRecord obj=(VideoRecord)cls.newInstance();

obj.setName("我是谁");

System.out.println(obj.getName());
反射2
//动态创建对象
String className = "cn.kgc.ref.VideoRecord";
try {
Class cls = Class.forName(className);

Constructor<VideoRecord> con = cls.getConstructor(new Class[] {
Integer.class, String.class, Date.class });

VideoRecord vr = con.newInstance(new Object[] { 1001, "测试",
DateUtil.getDate("2017-12-15") });

System.out.println(vr.getName());

vr.print();

 

 

 

 

 

 


===========================《注解Annotation》====================
1内部注解
@Override 注解方法
@Deprecated 指定方法已过期
@SuppressWarnings 组织编译器警告
注意@SuppressWarnings({"uncheck","fallthrough"})有俩个必须加大括号

2元注解 用在自编译注解上面
@Target
@Retention
3元注解和自编译注解一起使用
---自定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

俩个元注解
@Target(ElementType.METHOD)//定义这个注解只能用在方法处
@Retention(RetentionPolicy.RUNTIME)//定义这个注解可以被反射
public @interface TestAnnotation {
int age() default 20;//定义年龄常量 默认值20
}

 


---自定义注解的使用
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class Person {
private int age;

public int getAge() {
return age;
}

@TestAnnotation(age = 15)
public void setAge() {
// 反射读取
try {
Method mt = Person.class.getMethod("setAge");
Annotation[] anns = mt.getAnnotations();

for (Annotation ann : anns) {
if (ann instanceof TestAnnotation) {
TestAnnotation ta = (TestAnnotation) ann;
int age = ta.age();
if (age < 18) {
System.out.println("未成年");
} else {
System.out.println("具备选举权");
}
}

}

} catch (Exception e) {
// TODO: handle exception
}

}

public static void main(String[] args) {
Person person = new Person();
person.setAge();
}
四个元注解类型
@Target 指定被其修饰的注解能用于修饰哪些程序元素 成员变量value为ElementType 枚举类型
@Retention 指定该注解可使用反射读取 成员变量value:RetentionPolicy 枚举类型
@Documented 指定被其修饰的注解将被JavaDoc工具提取成文档
@Inherited 指定被其修饰的注解将具有继承性


-----------------《多线程》-------------------------------------------
进程 应用程序的执行实例 线程 进程中执行的最小单位

线程的状态 新生 可运行 阻塞 死亡
Thread.currentThread().getName()获得当前线程的名字

1线程的创建和启动
2线程的状态
3线程的调度
4同步机制

----------------------------使用Thread-------
1 public class MyThread extends Thread {
public MyThread() {
}
public MyThread(String name) {
super(name);
}

public void run() {
for (int i = 1; i <= 100; i++) {
// 获取当前线程的名称
System.out.println(Thread.currentThread().getName() + ":i=" + i);
}
}

}
public class Test {

public static void main(String[] args) {
//打印当前线程的名称
//System.out.println(Thread.currentThread().getName());

//创建线程对象(新生状态)
MyThread th1=new MyThread("子线程1");
//启动线程(线程处于可运行状态)
th1.start();


MyThread th2=new MyThread("子线程2");
//启动线程
th2.start();
}
让类继承thread这个类
创建线程对象(新生状态)
//启动线程(线程处于可运行状态
可以创建多个线程
--------------------《使用Runnable接口》---------------------意思是可运行
public class MyThread implements Runnable {
public void run() {
for (int i = 1; i <= 100; i++) {
// 获取当前线程的名称
System.out.println(Thread.currentThread().getName() + ":i=" + i);
}
}
}

public static void main(String[] args) {
// 创建线程对象
MyThread mt = new MyThread();

Thread th1 = new Thread(mt);
th1.setName("子线程1");

// 启动线程
th1.start();

Thread th2 = new Thread(mt);
th2.setName("子线程2");

// 启动线程
th2.start();
------------------《jion的使用》
public class MyThread extends Thread {
public MyThread() {

}
public MyThread(String name) {
super(name);
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
// 获取当前线程的名称
System.out.println(Thread.currentThread().getName() + ":i=" + i);
}
}
}
for (int i = 0; i < 10; i++) {
if(i==5){
//创建线程对象(新生状态)
MyThread th1=new MyThread("子线程1");
//启动线程(线程处于可运行状态)
th1.start();
try {
th1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 获取当前线程的名称
System.out.println(Thread.currentThread().getName() + ":i=" + i);
}
//处于可运动状态 将主线程转为阻塞状态
------------------------------《yield》
public class MyThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
if(i==3){
//线程的礼让 暂停当前正在执行的线程对象,并执行其他线程
Thread.yield();
}
// 获取当前线程的名称
System.out.println(Thread.currentThread().getName() + ":i=" + i);
}
}

}
public static void main(String[] args) {
// 创建线程对象
MyThread mt = new MyThread();

Thread th1 = new Thread(mt, "子线程1");
// 启动线程
th1.start();

Thread th2 = new Thread(mt, "子线程2");

// 启动线程
th2.start();

}
//处于就绪状态 不转为阻塞状态//不一定礼让

---------------------------《同步使用》
public void run() {
for (int i = 0; i < 5; i++) {
makeWithdrawal(100);
if(acct.getBalance()<0){
System.out.println("账户透支了");
}
}

}
/*//1线程同步方法
private synchronized void makeWithdrawal(int amt) {
if(acct.getBalance()>=amt){
System.out.println(Thread.currentThread().getName()+"准备取款");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
acct.withdraw(amt);
System.out.println(Thread.currentThread().getName()+"完成取款");
}else{
System.out.println("余额不足支付"+Thread.currentThread().getName());
System.out.println("你的余额是"+acct.getBalance());
}
}*/
//2线程同步代码块
private synchronized void makeWithdrawal(int amt) {
synchronized (acct) {
if(acct.getBalance()>=amt){
System.out.println(Thread.currentThread().getName()+"准备取款");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
acct.withdraw(amt);
System.out.println(Thread.currentThread().getName()+"完成取款");
}else{
System.out.println("余额不足支付"+Thread.currentThread().getName());
System.out.println("你的余额是"+acct.getBalance());

}
-----------------------------------《网络编程技术》---------------------------------------------------
c/s(客户端)列如qq 客户端到 服务器的应用程序
b/s(浏览器)列如淘宝 浏览器 到 服务器的应用程序

web服务器--使用tomcat开发


局域网 城域网 广域网
ip地址最大的取值范围0-255
端口的取值0-65535
1 查看自己ip cmd-ipconfig
2 ping 是测试是否地址畅通
3 BindException 这些错误通常发生在端口正在使用中或无法分配所请求的本地地址时
4 SocketException 抛出此异常指示在底层协议中存在错误,如 TCP 错误
5 -------TCP协议
服务器端的创建
//创建绑定到特定端口的服务器套接字
ServerSocket server=new ServerSocket(8888);
System.out.println("服务器启动侦听功能");
Socket socket=server.accept();//创建侦听。。。。。
-----列如
/**
* 服务器端
* @author Administrator
*
*/
public class Server {
public static void main(String[] args) {
ServerSocket server=null;
try {
//创建绑定到特定端口的服务器套接字
server=new ServerSocket(8888);
System.out.println("服务器侦听中。。。。");
Socket socket=server.accept();
//发送信息到客户端(写用的是)
PrintWriter out=new PrintWriter(socket.getOutputStream(),true);
//PrintWriter带参构造的是字节输出流
String str="服务器说;发送信息";
out.print(str);

//接受客户端发出的信息
BufferedReader bf=new BufferedReader
(new InputStreamReader(socket.getInputStream()));
String str1=bf.readLine();
System.out.println("客户端的回复: "+str1);
} catch (IOException e) {
e.printStackTrace();
}finally{
if( server!=null){
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

客户端的创建
//创建客户端套接字
Socket socket=new Socket("173.16.1.108", 8888);
-------------列如
/**
* 客户端
*/
public static void main(String[] args) {
Socket socket=null;
try {
//创建套接字的对象 带有特定的ip地址和端口
socket=new Socket("173.16.1.108", 8888);
//接受服务器发送的信息
BufferedReader bf=new BufferedReader
(new InputStreamReader(socket.getInputStream()));
String str=bf.readLine();
System.out.println("客户端接受 服务器发送的消息"+str);

//向服务器发送消息
String str1="你好 服务器";
PrintWriter out=new PrintWriter(socket.getOutputStream(),true);
out.print(str1);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
--------------------------------------《xml》--------------------------------------------------------

element 元素 document文件 builder建造 node节点 Attribute属性 node.getTextContent获得文本内容
命名空间
用来标识元素或者属性,防止重名解析冲突。
xmlns:[前缀]="命名空间的uri"
XML验证
DTD验证
Schema验证


1含义 可扩展标记语言
2特点 具有层次化与平台 和操作系统无关 作用 持久化数据存储 数据交换 数据配置
3<元素名 属性=“属性值”>多个属性之间用空格隔开
4如果有多个特殊字符可以
<![CDATA[放入内容]]>

< ---&lt;
>----&gt;
&---&amp;
"---&quot;
'---&apos;
5 注释 <!-- -->
6 空元素<name/>
7 属性可以加在任何一个元素的起始标签上,但不能加在结束标签上


doc=db.parse(new FileInputStream(path));可以直接加载xml的位置 也可以加载一个字节输入流读出来的文件对应的String值 文件--xml

8 xml解析技术 -----------------------------《DOM》-------------------------- 基于xml树结构 元素节点 文本节点 属性节点

9转换器的写法 将瞬时状态新建的DOM转换为持久状态的XML文件(修改添加删除都需要转换器)

//1得到转换器工厂
TransformerFactory tff=TransformerFactory.newInstance();
tff.setAttribute("indent-number",4);//指定缩进字数
//2得到转换器
Transformer tf=tff.newTransformer();
//3将dom转换xml文件
Source xmlSource=new DOMSource(doc);
Result outputTarget=new StreamResult(uri);
tf.setOutputProperty(outputkeys.ENCODING,"GBK")//指定编码格式
tf.setOutputProperty(outputkeys.INDENT,"yes")//指定缩进
tf.transform(xmlSource, outputTarget);

DOM解析包 org.w3c.dom
Node是超级接口 Element是子接口 NodeList接口只有俩个方法 .getlength() .iteam()

List<Book> list = new ArrayList<Book>();
try {
//1先创建解析器工厂生产对象
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
//2由工厂生产解析器生产对象
DocumentBuilder db=dbf.newDocumentBuilder();
//3由解析器对象加载这个xml文档 构建一个DOM树
Document d=db.parse("xml\\books.xml");
//获得根元素
Element e1=d.getDocumentElement();
System.out.println(e1.getTagName());//获得根元素的名字
//获得指定名字的子元素 NodeList是个接口只有俩个方法
NodeList nodelist1=e1.getElementsByTagName("book");
for (int i = 0; i < nodelist1.getLength(); i++) {
Book book=new Book();
Element e2=(Element)nodelist1.item(i);
//返回标签中指定属性id的值
book.setId(e2.getAttribute("id"));


// 包含此节点的所有子节点的
NodeList nodelist2=e2.getChildNodes();
for (int j = 0; j <nodelist2.getLength(); j++) {
Node node=nodelist2.item(j);
String nodename=node.getNodeName();
if("author".equals(nodename)){
//此属性返回此节点及其后代的文本内容
book.setAuther(node.getTextContent());
}
if("title".equals(nodename)){
book.setTitle(node.getTextContent());
}
if("des".equals(nodename)){
book.setDes(node.getTextContent());
}
}

list.add(book);
}
System.out.println("编号"+"\t"+"作者"+"\t"+"标题"+"\t\t\t"+"内容");
for (int i = 0; i < list.size(); i++) {
Book book=list.get(i);
System.out.println(book.getId()+"\t"+book.getAuther()+"\t"+book.getTitle()+"\t\tj"+book.getDes());
}

10------》添加图书
思路 也是就添加一个节点用doc.createElement("book")创建一个节点 再看他下面有没有子节点 用ebook.appendChild(eattuor);这是element方法把第二个节点变成子节点
最后拿到根节点把第一个大的节点变成根节点的子节点
public boolean addBook(Book book){
//获得根元素
Element root=doc.getDocumentElement();
//添加新节点
Element ebook=doc.createElement("book");
ebook.setAttribute("id", book.getId());
//添加子节点
Element eattuor=doc.createElement("attuor");
eattuor.setTextContent(book.getAuther());
ebook.appendChild(eattuor);
Element etitle=doc.createElement("title");
etitle.setTextContent(book.getTitle());
ebook.appendChild(etitle);
root.appendChild(ebook);
return saveXml(doc, uri);
}
11-----修改图书
也就是 根-找到修改元素的名字--拿到一个nolist集合 遍历一下拿到他的每一个属性 在获得他的每一个子元素(getChildNodes) 在把子元素的名字获取出来
判断是否和元素相等

public boolean updateBook(Book book) {
try {
if (doc != null) {
//找到符合条件的节点
//获得跟根元素
Element root=doc.getDocumentElement();
//获得指定元素
NodeList nodelist=root.getElementsByTagName("book");
//获取属性id 并赋值 给对象的编号
for (int i = 0; i < nodelist.getLength(); i++){
Element e=(Element)nodelist.item(i);
if(e.getAttribute("id").equals(book.getId())){
NodeList nl=e.getChildNodes();
for (int j = 0; j < nl.getLength(); j++) {
Node node=nl.item(j);
String nodeName=node.getNodeName();
if("author".equals(nodeName)){
node.setTextContent(book.getAuther());
}
if("title".equals(nodeName)){
node.setTextContent(book.getTitle());
}
if("des".equals(nodeName)){
node.setTextContent(book.getDes());
}
}
}
}
}
} catch (Exception e) {
// TODO: handle exception
}
return BookServiceimpl.saveXml(doc, uri);
}*/

12----删除图书
先找到跟元素 在根据名字(getElementsByTagName)获得要删除的元素 遍历一下如果属性一样的话就可以删除root.removeChild(e);

public boolean deleteBook(Book book) {
try {
if (doc != null) {
//找到符合条件的节点
//获得跟根元素
Element root=doc.getDocumentElement();
//获得指定元素
NodeList nodelist=root.getElementsByTagName("book");
//获取属性id 并赋值 给对象的编号
for (int i = 0; i < nodelist.getLength(); i++){
Element e=(Element)nodelist.item(i);
if(e.getAttribute("id").equals(book.getId())){
root.removeChild(e);
}

}
}
} catch (Exception e) {
// TODO: handle exception
}
return BookServiceimpl.saveXml(doc, uri);
}

 

 

 

--------------------------------《DOM4J解析》----------------------------
1要有架包 后缀是.jar lib代表类库的意思
2获得解析器的方法
SAXReader sr=new SAXReader();
Document doc=sr.read(uri);

------------------------------《使用DOM4J查看图书》----------------

//1获得解析器
SAXReader sr=new SAXReader();
Document doc=sr.read(uri)
//获得转换器 保存dom树到xml文档
OutputFormat format=OutputFormat.createPrettyPrint();//漂亮的输出格式
format.setEncoding("GBK");//指定编码格式
XMLWriter xw=new XMLWriter(new FileWriter(uri),format);//xml保存dom树
xw.write(doc);
xw.close();

 

2 查看图书 的方法read()3getRootElement() 4root.elements()5 e.attribute("id").getValue()6 Iterator it=e.elementIterator()7 String name=child.getName();8child.getTextTrim()
3 添加图书 用到的方法是 doc.getRootElement()---root.addElement("book");---ebook.addAttribute()--子元素ebook.addElement("author");--eauthor.setText(book.getAuthor());
4 修改图书 根据id修改的 用到的方法是 doc.getRootElement();--root.elements(); --遍历 if (book.getId().equals(e.attributeValue("id")))-- 遍历子元素 for (Iterator it = e.elementIterator(); it.hasNext();)
String name = child.getName();//获得子元素的名字 child.setText(book.getAuthor());
5 删除图书 先找到根doc.getRootElement(); 在找到book元素List<Element> elist = root.elements("book"); 遍历if (book.getId().equals(e.attributeValue("id"))) 如果id和book一样则删除
//用根元素删除 e.getParent().remove(e); 用的是父类删


------------------------------《查看图书》
public static void main(String[] args) {
List<Book>list=new ArrayList<Book>();
//1获得解析器
SAXReader sr=new SAXReader();

try {
//2获得document
Document doc=sr.read("xml\\dom4j.xml");
//3获得根元素 跟对象
Element root=doc.getRootElement();
//通过找名字获得需要的元素集合
List<Element> elist=root.elements("book");
for (Element e : elist) {
Book book=new Book();
book.setId(e.attribute("id").getValue());//获得book属性id的值

//获得所有book下面的子元素 带有迭代器的
for (Iterator it=e.elementIterator();it.hasNext() ;) {
Element child=(Element)it.next();
String name=child.getName();//获得所有book下面子元素的名字
if("author".equals(name)){
book.setAuther(child.getTextTrim());//获得author所对应的文本内容
}
if("title".equals(name)){
book.setTitle(child.getTextTrim());
}
if("des".equals(name)){
book.setDes(child.getTextTrim());
}
}
list.add(book);
}
System.out.println("编号"+"\t"+"作者"+"\t"+"标题"+"\t\t\t"+"内容");
for (int i = 0; i < list.size(); i++) {
Book book=list.get(i);
System.out.println(book.getId()+"\t"+book.getAuther()+"\t"+book.getTitle()+"\t\t"+book.getDes());
}

----------------------《查看图书》--------------------------------
public List<Book> listBook() {
List<Book>list=new ArrayList<Book>();
//获得解析器 已获得
//获得根元素
Element root=doc.getRootElement();
//找book元素
List<Element> elist=root.elements("book");
for (Element e : elist) {
Book book=new Book();
//在获得book的属性值
//book.setId(e.attribute("id").getValue());
book.setId(e.attributeValue("id"));
//在找book下面的子元素
for (Iterator it = e.elementIterator(); it.hasNext();) {
Element child=(Element)it.next();//遍历拿出每一个子元素
String nodename=child.getName();//获得所有子元素的名字
if("author".equals(nodename)){
book.setAuthor(child.getText());//获得author的文本内容
}
if("title".equals(nodename)){
book.setTitle(child.getTextTrim());//在获得文本内容的时候去掉空格
}
if("des".equals(nodename)){
book.setDes(child.getText());
}
}
list.add(book);
}
return list;
}

----------------------------《添加图书》----------------------
//添加图书
public boolean addBook(Book book){
boolean flag=false;
try {
//获得根元素
Element root = doc.getRootElement();
//添加book元素
Element ebook = root.addElement("book");
ebook.addAttribute("id", book.getId());
//添加book的子元素(author)
Element eauthor = ebook.addElement("author");
eauthor.setText(book.getAuthor());
//添加book的子元素(title)
Element etitle = ebook.addElement("title");
etitle.setText(book.getTitle());
//添加book的子元素(des)
Element edes = ebook.addElement("des");
edes.setText(book.getDes());
BookService.saveXml(doc, uri);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
用到的方法是 doc.getRootElement()---root.addElement("book");---ebook.addAttribute()--子元素ebook.addElement("author");--eauthor.setText(book.getAuthor());


------------------------《修改图书》---------------
根据id修改的 用到的方法是 doc.getRootElement();--root.elements(); --遍历 if (book.getId().equals(e.attributeValue("id")))-- 遍历子元素 for (Iterator it = e.elementIterator(); it.hasNext();)
String name = child.getName();//获得子元素的名字 child.setText(book.getAuthor());
//修改图书
public boolean updateBook(Book book) {
boolean flag=false;
try {
//找到根元素
Element root = doc.getRootElement();
//找到book元素的集合
List<Element> elist = root.elements();
for (Element e : elist) {
//判断属性是否和book的一样
if (book.getId().equals(e.attributeValue("id"))) {
for (Iterator it = e.elementIterator(); it.hasNext();) {
Element child = (Element) it.next();//拿到每一个子元素
String name = child.getName();//获得子元素的名字
if ("author".equals(name)) {
child.setText(book.getAuthor());
}
if ("title".equals(name)) {
child.setText(book.getTitle());
}
if ("des".equals(name)) {
child.setText(book.getDes());
}
}
}
}
BookService.saveXml(doc, uri);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
---------------------------《删除图书》---------------

root.remove(e);
//删除图书
public boolean delBook(Book book) {
boolean flag=false;
try {
//获得根元素
Element root = doc.getRootElement();
//找到book这个节点
List<Element> elist = root.elements("book");
for (Element e : elist) {
if (book.getId().equals(e.attributeValue("id"))) {//book和图书id一样就删除
//用根元素删除 e.getParent().remove(e);
root.remove(e);
}
}
BookService.saveXml(doc, uri);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;

 


---------------------------《junit测试》-------------
第三方的 需要架包

创建一个没有返回值没有参数的方法 上面加上注解 @Test
@Test//测试添加
public void addBookTest(){
Book book=new cn.kgc.booksys.Book("004","小伟","西游记","好看");
boolean flag=se.addBook(book);
//断言1
Assert.assertTrue(flag);
System.out.println("添加ok");
/*断言2
Assert.assertEquals(true, flag);*/
}

项目开发过程
1 可行性分析
2 项目需求说明书(需求分析师)
3 概要设计 详细设计
4 软件编写
5 代码测试
6 项目合并 安装 部署(软件实施工程师)


-------------------《单例模式》-------------------------
Properties集合和配置文件一起使用 文件格式后缀是.Properties 配置文件里放进去一串英文对应要使用的端口 或者xml文件
1
2
3
private static Properties p=null;//类似Map集合 存储K-V对 但必须都是String类型的
private static Configutil t=null;

//1 文件的读取--私有的构造方法 也就意味不能再外界new对象了
private Configutil(){
try {
p=new Properties();
p.load(new FileInputStream("config\\1.properties"));//用字节输出流的形式读取文件
} catch (Exception e) {
e.printStackTrace();
}
}
//2 在本类中创建唯一的实例 Test对象
public static Configutil newInstance(){
if(t==null){
t=new Configutil();
}
return t;//如果对象存在 直接返回t就行了
}

//3 输入K值 得到唯一对应的V值
public String getValue(String key){
if(p!=null){
return p.getProperty(key);
}else{
return null;
}
}
}

public static void main(String[] args) {
//单列模式的类不能再new了 通过调方法创建对象
Configutil con=Configutil.newInstance();
//获得配置文件中socket.server.port对应的端口号
//这样就不用再源代码中修改端口号了 直接在文件中修改端口号
String duankou=con.getValue("socket.server.port");
System.out.println(duankou);
}
}
工程打包 把所需要的类打包- export---jar包

 

 

 


/ /注意:泛型集合中的类型必须是引用类型
ArrayList<Integer> list2=new ArrayList<Integer>();

Collections 只能对List集合排序

1.java的基本数据类型分为两类:数值型和非数值型
2.数值型:byte、short、int、long、float、double 非数值型:char、boolean

//将String转换为枚举类型
student.setSex(Genders.valueOf(Genders.class, sex));

root.elements();//获得所有的元素 如果带有参数就是获得指定名字的元素


String 是不可变的对象 修改的时候等同于生成一个新的对象
StringBuffer 是可变的字符串 对它本身就行修改的

--------------------------使用字节输入输出流复制文件
public static boolean getbigFile(String uri,String gouri){
boolean flag=false;
File f=null;
InputStream fr=null;
OutputStream fo=null;
f=new File(uri);
try {
if(f.exists()){
fr=new FileInputStream(uri);
fo=new FileOutputStream(gouri,true);
byte[] bytes=new byte[1024];
if(fr.available()<1024){
bytes=new byte[fr.available()];
fr.read(bytes);
fo.write(bytes);
flag=true;
}else{
int len=fr.read(bytes, 0, bytes.length);
while(len!=-1){
fo.write(bytes, 0, len);
}
flag=true;
}
}else{
System.out.println("文件不存在");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
fo.flush();
fo.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return flag;
}
@SuppressWarnings("static-access")
public static void main(String[] args) {
String uri="D:ceshi/1.txt";
String gouri="D:ceshi/2.txt";
boolean flag=new Copy1().getbigFile(uri, gouri);
if(flag){
System.out.println("复制成功");
}else{
System.out.println("复制失败");
}

}

-----------------------------------------------使用buffered字符输入输出复制
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class Copy2 {

public static boolean getbigFile(String soucepath, String targetpath){
boolean flag=false;
InputStreamReader isr=null;
BufferedReader bf=null;
BufferedWriter bw=null;
try {
isr=new InputStreamReader(new FileInputStream(soucepath));//可以指定编码格式
bf=new BufferedReader(isr);
bw=new BufferedWriter(new FileWriter(targetpath));
String str;
while((str=bf.readLine())!=null){
bw.write(str);
bw.newLine();
}
flag=true;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
bw.flush();
bw.close();
isr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return flag;
}
@SuppressWarnings("static-access")
public static void main(String[] args) {
String soucepath="D:ceshi/1.txt";
String targetpath="D:ceshi/2.txt";
boolean flag=new Copy2().getbigFile(soucepath, targetpath);
if(flag){
System.out.println("复制成功");
}else{
System.out.println("复制失败");
}
}


}


反射 1拿到CLass对象 类的完整名字String classname="xuliehua.Video";xuliehua是包名 Video是类名 不用写后缀

//搭建的步骤 1创建实体类 2创建一个接口提供对实体类增删改查的办法3 在创建一个imp去实现接口里的方法

/ /要想多线程就要1 继承thread类 或者实现Runnable
//重写run方法
//创建线程对象
//Thread t=new Thread要使用多线程的对象)
//t.start


Dom解析思路
思路分析: 1.创建Book类(属性为:编号、书名、作者、描述) 2.创建BookBiz类,声明一个List集合 3.创建一个方法,在方法中通过DOM解析XML文档数据,每次读取一个book元素,生成一个Book对象,将book元素的值分别赋值给Book对象的每个属性,最后将对象放入List集合中 4.遍历List集合,打印集合中的元素


--------------------------出现的问题
map是没有下标的 K-V

 

 

 

 



 


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

 

转载于:https://www.cnblogs.com/niweiniwei/p/8994234.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值