JAVA
一.类和对象
1.程序的代码(review)
二.异常处理
1.程序代码(review)
//(1)InputMismatchException异常类
import java.util.InputMismatchException;
import java.util.Scanner;
class count {
public static void main(String[] args) {
try {
int a;
int b;
char s;
j();//菜单
System.out.println("请输入运算数:");
Scanner n1 = new Scanner(System.in);
a = n1.nextInt(); b = n1.nextInt();
System.out.println("请输入运算符:");
s=n1.next().charAt(0);
System.out.println("计算结果为:");
if(s=='+')
{
System.out.println("**********************");
System.out.printf("*%d+%d=%d *",a,b,(a+b));
System.out.println("\n**********************");
}
else if(s==('-')) {
System.out.println("**********************");
System.out.printf("*%d-%d=%d *", a, b, (a - b));
System.out.println("\n**********************");
}
else if(s==('*')) {
System.out.println("**********************");
System.out.printf("*%d*%d=%d *", a, b, (a * b));
System.out.println("\n**********************");
}
else if(s==('/')) {
System.out.println("**********************");
System.out.printf("%d/%d=%d *", a, b, (a / b));
System.out.println("\n**********************");
}
}
catch (InputMismatchException e){
System.out.println("**********************************");
System.out.println("*您输入的运算数不是数字,请重新输入*");
System.out.println("**********************************");
}
catch (ArithmeticException e){
System.out.println("**************************************");
System.out.println("*您输入的除法表达式中除数为0,请重新输入*");
System.out.println("***************************************");
}
}
static void j(){
System.out.println("***********************");
System.out.println("* 简易计算器 *");
System.out.println("***********************");
}
}
//自定义异常类
import java.util.Scanner;
class triangle{
private int a;
private int b;
private int c;
public triangle(int a,int b,int c)throws triangleException {
setA(a);
setB(b);
setC(c);
}
public void setA (int a){
this.a = a;
}
public int getA() {
return a;
}
public void setB(int b){
this.b=b;
}
public int getB(){
return b;
}
public void
setC(int c){
this.c=c;
}
public int getC(){
return c;
}
public void count()throws triangleException{
if((a+b)>c&&(a+c)>c&&(b+c)>a)
System.out.printf("三角形周长为;%d",(a+b+c));
else
throw new triangleException("无效三角形三边值");
}
}
class Test{
public static void main(String[] args)throws triangleException {
try{ int m;
int n;
int w;
System.out.println("请输入三角形三边的值");
Scanner n1 = new Scanner(System.in);
m=n1.nextInt();n=n1.nextInt();w=n1.nextInt();
triangle m1 = new triangle(m,n,w);
m1.count();
}
catch(triangleException e){
System.out.println("无效的三角形三边值,请重新输入");
}
}
}
public class triangleException extends Exception{
public triangleException(String s){
super(s);
}
}
三.GUI
1.简单设置
(1)setResizable(false); 界面的大小固定
(2)setVisible(true);界面可视化
(3)//(1)即便使用布局器也可以通过setPreferredSize,向布局器建议该组件显示的大小
b3.setPreferredSize(new Dimension(180, 40));
(4)//为便签设置颜色
JLabel l = new JLabel("LOL文字");
//文字颜色
l.setForeground(Color.red);
2.四种布局管理器
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//BorderLayout:东西南北中布局
public class Layout {
public static void main(String[] args) {
Frame frame = new Frame("TestBorderLayout");
//设置东西南北布局
Button East = new Button("East");
Button West = new Button("West");
Button South = new Button("South");
Button North = new Button("North");
Button Center= new Button("Center");
frame.add(East, java.awt.BorderLayout.EAST);
frame.add(West, java.awt.BorderLayout.WEST);
frame.add(South, java.awt.BorderLayout.SOUTH);
frame.add(Center, java.awt.BorderLayout.CENTER);
frame.add(North, java.awt.BorderLayout.NORTH);
frame.setSize(300,600);
frame.setLocation(500,500);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
//FlowLayout:流式布局
class FlowLayout {
public static void main(String[] args) {
Frame frame = new Frame();//窗口
//组件-按钮(发送)
Button button1 = new Button("button1");
Button button2 = new Button("button2");
Button button3 = new Button("button3");
//设置流式布局
frame.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER));
frame.setSize(200,300);
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.setVisible(true);
}}
//GridLayout表格布局
public class GridLayout {
public static void main(String[] args) {
Frame frame = new Frame();
Button btn1= new Button("btn1");
Button btn2= new Button("btn2");
Button btn3= new Button("btn3");
Button btn4= new Button("btn4");
frame.setLayout(new java.awt.GridLayout(2,2));
frame.add(btn1);
frame.add(btn2);
frame.add(btn3);
frame.add(btn4);
frame.setVisible(true);
}
}
3.常用的事件监听
//(1)窗口关闭事件
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//(2)在标签上添加图片
//(2.1)
JLabel l = new JLabel();
ImageIcon i=new ImageIcon(getClass().getResource("tx 1.jpg"));
l.setIcon(i);
l.setSize(1,1);
//(2.2待证)
JLabel l = new JLabel();
//根据图片创建ImageIcon对象
ImageIcon i = new ImageIcon("e:/project/j2se/shana.png");
//设置ImageIcon
l.setIcon(i);
//label的大小设置为ImageIcon,否则显示不完整
l.setBounds(50, 50, i.getIconWidth(), i.getIconHeight());
//(3)鼠标监听
public class panel {
public static void main(String[] args) {
Frame frame = new Frame();
Panel panel = new Panel();
//设置布局
frame.setLayout(null);
//坐标
frame.setBounds(300,300,500,500);
frame.setBackground(new Color(40,161,35));
//设置坐标,相对于frame
panel.setBounds(50,50,400,400);
panel.setBackground(new Color(193,15,60));
frame.add(panel);
frame.setVisible(true);
// 对按钮添加鼠标的进入事件
redButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
f.setBackground(Color.RED);
}
});
redButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseExited(MouseEvent e) {
f.setBackground(Color.black);
}
});
4.程序代码(review)
//(1)图形界面的加法运算
import java.awt.*;
import java.awt.FlowLayout;
import java.awt.event.*;
public class Sund {
public static void main(String[] args) {
new Calculator();
}
}
//计算机类
class Calculator extends Frame{
public Calculator(){
TextField num1 = new TextField(10);
TextField num2 = new TextField(10);
TextField num3 = new TextField(20);
Button button = new Button("=");
button.addActionListener(new MyActonlister(num1,num2,num3));
Label label = new Label("+");
setLayout(new FlowLayout());
add(num1);
add(label);
add(num2);
add(button);
add(num3);
setVisible(true);
//窗口关闭事件
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});}
//事件监听器类
class MyActonlister implements ActionListener {
private TextField num1,num2,num3;
public MyActonlister(TextField num1,TextField num2,TextField num3) {
this.num1 = num1;
this.num2 = num2;
this.num3 = num3;
}
@Override
public void actionPerformed(ActionEvent e) {
int n1 = Integer.parseInt(num1.getText());
int n2 = Integer.parseInt(num2.getText());
num3.setText((" "+(n1+n2)));
num1.setText(" ");
num2.setText(" ");
}
}
}
//(2)将图形界面文本框中的内容在控制台界面显示
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Test1 {
public static void main(String[] args) {
new MyFrme();
}
}
class MyFrme extends Frame {
public MyFrme(){
TextField textField = new TextField();
add(textField);
//监听这个文本框输入的文字
MyActionListener2 myActionListener2 = new MyActionListener2();
textField.addActionListener(myActionListener2);
//设置替换编码
textField.setEchoChar('*');
setVisible(true);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
//事件的监听
class MyActionListener2 implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
TextField field = (TextField) e.getSource();//获得一个对象,
System.out.println(field.getText());
field.getText();
field.setText("");//null
}
}
//(3)打折购买,计算实付金额
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*程序运行后,用户在图形界面输入购物金额,程序计算经过优惠后顾客应付的实际金额,
结果保留两位小数,并告知用户。
*/
class buy2 {
public static void main(String[] args) {
new shopping1();
}
}
class shopping1 extends JFrame{
public shopping1(){
Container z = getContentPane();
setSize(500,400);
setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel p1 = new JPanel();
JLabel n1 = new JLabel("购物金额");
n1.setFont(new Font("宋体",Font.PLAIN,20));
JTextField c1 = new JTextField(10);
p1.add(n1);
p1.add(c1);
JPanel p2=new JPanel();
JButton b1 = new JButton("最终金额");
b1.setFont(new Font("宋体",Font.PLAIN,20));
JTextField c2=new JTextField(10);
p2.add(b1);
p2.add(c2);
MyactionListener my1 = new MyactionListener(c1,c2);
b1.addActionListener(my1);
z.add(p1);
z.add(p2);
setVisible(true);
}
}
class MyactionListener implements ActionListener{
private JTextField c1,c2;
public MyactionListener(JTextField c1,JTextField c2){
this.c1=c1;
this.c2=c2;
}
@Override
public void actionPerformed(ActionEvent e) {
int n1=Integer.parseInt(c1.getText());
for (int i = 0; i < 4; i++) {
if (n1 > 500 && n1 <= 1000)
c2.setText(String.valueOf(n1*0.95));
if (n1 > 1000 && n1 <= 1500)
c2.setText(String.valueOf(n1 * 0.90));
if (n1 > 1500 && n1 <= 2500)
c2.setText(String.valueOf(n1 * 0.85));
if (n1 > 2500)
c2.setText(String.valueOf(n1 * 0.80));
}
}
}
//(4)抽奖活动
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*编写一个简单的模拟抽奖程序(模拟抽奖3.0),
程序运行后会随机生成5个1~16幸运号码,然后在图形界面提示“请您抽奖”,
等待用户输入5个1~16不重复的整数作为抽奖号码。开始抽奖后,
程序判断用户输入的号码与系统生成的幸运号码是否一致,给出用户中奖结果。
抽奖规则:如果用户输入的号码中分别有5、4、3个号码与幸运号码一致,
则分别判定为一等奖、二等奖、三等奖,否则判定为未中奖。
要求给出必要的提示信息,如输入号码的数值范围限制;
提供关闭按钮或菜单项,当用户希望结束抽奖时可以自主退出程序的运行。*/
public class sunw {
public static void main(String[] args) {
new award();
}
}
class award extends JFrame{
public award(){
Container z = getContentPane();
setSize(900,300);
setLocation(300,300);
setLayout(new GridLayout(2,1));//表格布局(2.1)
JPanel p1 = new JPanel();
//JLabel n1 = new JLabel("请您抽奖");
//n1.setFont(new Font("宋体",Font.PLAIN,20));
JLabel n2=new JLabel("输入5个1~16不重复的整数");
n2.setFont(new Font("宋体",Font.PLAIN,20));
JTextField c1 = new JTextField(10);
JTextField c2 = new JTextField(10);
JTextField c3 = new JTextField(10);
JTextField c4 = new JTextField(10);
JTextField c5 = new JTextField(10);
JButton b0 = new JButton("开始抽奖");
b0.setFont(new Font("宋体",Font.PLAIN,20));
//p1.add(n1);
p1.add(n2);
p1.add(c1);
p1.add(c2);
p1.add(c3);
p1.add(c4);
p1.add(c5);
p1.add(b0);
JPanel p2=new JPanel();
JLabel n3 = new JLabel("中奖结果");
n3.setFont(new Font("宋体",Font.PLAIN,20));
JTextField d1=new JTextField(10);
Myaclistener01 m1= new Myaclistener01(c1,c2,c3,c4,c5,d1);
b0.addActionListener(m1);
//监听的按钮:当用户希望结束抽奖时可以自主退出程序的运行.
JButton b2 = new JButton("结束抽奖");
n3.setFont(new Font("宋体",Font.PLAIN,20));
b2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
p2.add(n3);
p2.add(d1);
p2.add(b2);
z.add(p1);
z.add(p2);
setVisible(true);
}
}
class Myaclistener01 implements ActionListener{
private JTextField c1,c2,c3,c4,c5,d1;
public Myaclistener01(JTextField c1,JTextField c2,JTextField c3 ,JTextField c4 ,JTextField c5,JTextField d1){
this.c1=c1;
this.c2=c2;
this.c3=c3;
this.c4=c4;
this.c5=c5;
this.d1=d1;
}
@Override
public void actionPerformed(ActionEvent e) {
int n1=Integer.parseInt(c1.getText());
int n2=Integer.parseInt(c2.getText());
int n3=Integer.parseInt(c3.getText());
int n4=Integer.parseInt(c4.getText());
int n5=Integer.parseInt(c5.getText());
//生成5个随机数
int a[] = {0, 0, 0, 0, 0};
int b,z;
for (int j = 0; j < 5; j++) {
b = (int) (Math.random() * 16 + 1);
for (int i = 0; i < 5; i++) {
if (b == a[i]) {
b = (int) (Math.random() * 16 + 1);
i = -1;
}
}
a[j] = b;
}
int t1=2,t2=2,t3=2,t4=2,t5=2;
for (int i = 0; i < 5; i++) {
if(n1==a[i])
t1=1; }
for (int i = 0; i < 5; i++) {
if(n2==a[i])
t2=1; }
for (int i = 0; i < 5; i++) {
if(n3==a[i])
t3=1; }
for (int i = 0; i < 5; i++) {
if(n4==a[i])
t4=1; }
for (int i = 0; i < 5; i++) {
if(n5==a[i])
t5=1; }
int t[]=new int[5],sum=0;
t[0]=t1; t[1]=t2; t[2]=t3; t[3]=t4; t[4]=t5;
for(int i=0;i<5;i++)
{
if(t[i]==1)
sum=sum+1;
}
if (sum==5)
d1.setText("恭喜您中了一等奖");
else if (sum==4)
d1.setText("恭喜您中了二等奖!");
else if (sum==3)
d1.setText("恭喜您中了三等奖");
else
d1.setText("很遗憾,您未中奖!");
}
}
5.其他
//按钮组
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
class linshi {
public static void main(String[] args) {
new l1("shiyan");
}
}
class l1 extends JFrame{
public l1(String tile){
setTitle("实验");
setSize(100,300);
setLocation(200,300);
Container z=getContentPane();
//setResizable(false);
JPanel w1 = new JPanel();
w1.setBackground(Color.blue);
w1.setLayout(new FlowLayout());
//按钮需要添加两次
JRadioButton j1 = new JRadioButton();
JRadioButton j2 = new JRadioButton();
JRadioButton j3 = new JRadioButton();
ButtonGroup n1 = new ButtonGroup();
n1.add(j1);
n1.add(j2);
n1.add(j3);
w1.add(j1);
w1.add(j2);
w1.add(j3);
add(w1);
setVisible(true);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}}
四.IDEA连接数据库
package com;
import java.sql.*;
public class jdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");//固定写法,加载驱动
//2.用户信息 和url
String url= "jdbc:mysql://localhost:3306/bmi? useUnicode=true&characterEncoding=utf8&useSSL=true";
String username="root";
String password="123456";
//3.连接成功,数据库对象 Connection:代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
//4.执行sql的对象 Statement :执行sql的对象
Statement statement = connection.createStatement();
//5执行sql的对象 去执行sql,可能存在结果,返回结果。
String sql="select * from student";
ResultSet resultSet = statement.executeQuery(sql);//返回的结果集,结果集封装了我们的全部查询出来的结果
while (resultSet.next()){
System.out.println("idstudent"+resultSet.getObject("idstudent"));
System.out.println("sname"+resultSet.getObject("sname"));
}
//6.释放连接
resultSet.close();
statement.close();
connection.close();
}
}
五.集合
5.1.集合的分类
单列:List(可重复) Set(不可重复)
双列:Map
注:以上均为结口,还需要具体的实现类 。具体如下
5.2Collection
5.2.1 Collection常用方法
import java.util.*;
/*
1.boolean add(E e) 给集合添加元素
2.boolean remove(Object o) 从集合中移除指定对象
3.void clear() 清空集合(返回为空值,可以直接用对象进行调用)
4.boolean contains(Object o)判断集合是否存在指定元素
5.boolean isEmpty() 判断集合是否为空
6.int size() 集合元素的个数
*/
public class Collectionk {
public static void main(String[] args) {
//多态的方式 创建Collection集合对象
Collection<String> a = new ArrayList<String>();
a.add("kangzhijian");
System.out.println(a.add("weijiaqi"));
System.out.println(a.remove("ai"));
a.clear();
System.out.println(a.contains("ai"));
System.out.println(a.isEmpty());
System.out.println(a.size());
//输出集合对象
System.out.println(a);
}
}
5.2.2 迭代器
import java.util.*;
/*
1.Iterator<E> iterator()返回此集合元素的迭代器,通过集合的iterator()方法得到
2.boolean hasNext();如果迭代具有更多元素 ,返回true
*/
public class CoT1 {
public static void main(String[] args) {
Collection<String> a=new ArrayList<String>();
a.add("kang");
a.add("zhi");
Iterator<String> it= a.iterator();//通过集合对象,获取迭代器对象
/*
System.out.println(it.next());
System.out.println(it.next());
System.out.println(it.next());
NoSuchElementException:表示请求的元素不存在
*/
//遍历集合的一种方法
while (it.hasNext()){
String s= it.next();
System.out.println(s);
}
}
}
5.2.3List 集合内容
List集合特点:
1.有序集合(也称为序列)
2.允许重复的元素
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/*
一:List特有的方法
1.void add(int index, E element) 在指定位置添加指定元素,返回值为空。
2.E remove(int index) 删除指定索引出的元素,返回被删除的元素。
3.E set(int index, E element) 修改指定索引处的元素,返回被修改的元素
4.E get(int index) 返回该指定索引处的元素
二:并发修改异常(ConcurrentModificationException)
(当不允许这样的修改时,可以通过检测到对象的并发修改的方法来抛出此异常。)
注:遍历集合,若有某元素,则添加新元素。
只能使用for循环遍历,迭代器遍历会出现并发修改异常(具体查源码)
三:增强for循环 (内部原理是一个迭代器)
*/
public class CcListk {
public static void main(String[] args) {
List<String> a=new ArrayList<String>();
a.add("hello");
a.add("world");
a.add(0,"java");
/*
IndexOutOfBoundsException :索引不存在异常
a.add(11,"k");
*/
System.out.println(a.remove(2));
System.out.println(a.set(0,"wen"));
System.out.println(a.get(0));
System.out.println("***************");
//遍历集合方法1 迭代器 (集合特有的遍历方式)
Iterator<String> it = a.iterator();
while(it.hasNext()){
String a1= it.next();
/*
出现并发修改异常(ConcurrentModificationException)
if(a1.equals("w")){
a.add("woor");
}*/
}
System.out.println("***************");
//遍历集合方法2 for循环 (带有索引的遍历方式)
for(int i=0;i<a.size();i++){
String s = a.get(i);
if(s.equals("w")) {
a.add("woor");
}
}
System.out.println("***************");
//遍历集合方法3 增强for循环 (最方便的遍历方式)
for (String s:a){
System.out.println(s);
/*
出现并发修改异常(ConcurrentModificationException)
(内部原理是一个迭代器)
if(s.equals("jian")){
a.add("jiann");
}
*/
}
//输出集合对象
System.out.println(a);
}
}
注:增强for循环
ListIterator:列表迭代器的相关内容
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
/*
1.ListIterator:列表迭代器
通过List集合的ListIterator()方法得到,所以说它是list集合特有的迭代器
用于允许程序员沿任一方向遍历列表的列表的迭代器,在迭代期间修改列表,并获取列表中迭代器的当前位置。
2. ListIterator中的常用方法:
E previous() 返回列表中的上一个元素,并向后移动光标位置。
boolean hasPrevious() 如果此列表迭代器在相反方向遍历列表时具有更多元素,则返回 true。
void remove() 从列表中删除 next()或 previous() (可选操作)返回的最后一个元素。
void set(E e) 用指定的元素(可选操作)替换 next()或 previous()返回的最后一个元素。
*/
public class CdListk {
public static void main(String[] args) {
List<String> a=new ArrayList<String>();
a.add("hello");
a.add("world");
a.add("java");
ListIterator<String> w = a.listIterator();
while(w.hasNext()){
String m=w.next();
if(m.equals("world")){
/*
Iterator: 没有添加方法
ListIterator:有 add()添加方法
因此可以使用 w 来调用add()方法 (具体可以进行查看源码)
*/
w.add("worrr");
}
}
System.out.println(a);
}
}
List集合常用子类:ArrayList,LinkedList
ArrayList: 底层数据结构是数组,查询快,增删慢
LinkedList:底层数据结构是链表,查询慢,增删快 . 特有方法(如下代码段)
import java.util.LinkedList;
/*
void addFirst(E e) 在该列表开头插入指定的元素
void addLast(E e) 将指定的元素追加到此列表的末尾。
E getFirst() 返回此列表中的第一个元素。
E getLast() 返回此列表中的最后一个元素。
E removeFirst() 从此列表中删除并返回第一个元素。
E removeLast() 从此列表中删除并返回最后一个元素。
*/
public class CeL {
public static void main(String[] args) {
LinkedList<String> a=new LinkedList<String>();
a.add("ka");
a.add("jian");
a.add("ni");
//void addFirst(E e) 在该列表开头插入指定的元素
a.addFirst("wo");
//void addLast(E e) 将指定的元素追加到此列表的末尾。
a.addLast("le");
//........
System.out.println(a);
}
}
5.2.5 Set集合内容
(1)Set集合的特点
1.不包含重复元素的集合
2.没有带索引的方法,所以不能使用普通的for循环遍历
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
// HashSet:对集合的迭代顺序不作任何保证
public class CfS {
public static void main(String[] args) {
Set<String> a=new HashSet<String>();
a.add("hello");
a.add("kan");
a.add("jian");
//遍历方式1 迭代器
Iterator<String> w=a.iterator();
while(w.hasNext()){
System.out.println(w.next());
}
//遍历方式2 增强for
for (String s:a){
System.out.println(s);
}
}
}
(2)哈希值:是JDK根据对象的地址或者字符串或者数字算出的int类型的数值
import WJQ.Test1.Student;
public class Cghashcod {
public static void main(String[] args) {
Student n1 = new Student("康智建",18);
//同一个对象的哈希值相同
System.out.println(n1.hashCode());//460141958
System.out.println(n1.hashCode());//460141958
System.out.println("***********************");
//默认情况下,不同对象的哈希值不同。 重写hashCode()方法可以实现相同
Student n2 = new Student("康智建",18);
System.out.println(n2.hashCode());//1163157884
System.out.println("***********************");
System.out.println("kang".hashCode());
System.out.println("kang".hashCode());//说明调用的为同一个对象
System.out.println("***********************");
System.out.println("重地".hashCode());//字符串重写了hashCost()方法
System.out.println("通话".hashCode());
}
}
(3)HashSet集合的特点
super(Set) 不包含重复元素的集合
没有带索引的方法,所以不能使用普通的for循环遍历
特有: 1.底层数据结构为哈希表
2.对集合的迭代顺序不作任何保证
(4)LinkedHashSet集合的特点
super(Set) 不包含重复元素的集合
没有带索引的方法,所以不能使用普通的for循环遍历
特有: 1.哈希表和链表实现的Set接口,具有可预测性的迭代次序
2.由链表保证元素有序,即存储与取出顺序一致
3.由哈希表保证元素唯一。
注:哈希表底层采用数组加链表的实现
(5)TreeSet集合的特点
super(Set) 不包含重复元素的集合
没有带索引的方法,所以不能使用普通的for循环遍历
特有: 1.元素有序,能够按照一定的规则进行排序,排序方式取决于构造方法
TreeSet():根据其元素的自然排序进行排序(123 or abc)
TreeSet(Comparator comparator):根据指定的比较器进行排序
import java.util.TreeSet;
public class St {
public static void main(String[] args) {
TreeSet<Integer> a= new TreeSet<Integer>();
a.add(1);
a.add(20);
a.add(13);
a.add(4);
for(Integer w:a){
System.out.println(w);
}
}
}
(6)自然排序Comparable的使用
即让元素所属的类实现Comparable接口,重写compareTo(T o)方法
//该重写的方法,放在学生类中。
@Override
public int compareTo(Student o) {
int num=this.getAge()-o.age;
int num2=num==0?this.name.compareTo(o.name)-o.age:num;
return num2;
}
(7)比较器排序Comparator的使用
即让集合构造方法接受Comparator的实现类对象。重写compare(T o1,T o2)方法
//学生类中没由Comparable接口和相应的方法,一般需要自定义类(该类连接Comparator接口)
TreeSet<Student> a=new TreeSet<Student>(new Comparator<Student>() {//匿名类的方式
@Override
public int compare(Student s1, Student s2) {
//s1,s2分别代表自然排序的this...和o...
int num= s1.getAge()-s2.getAge();
int num2=num==0?s1.getName().compareTo(s2.getName()):num;
return num2;
}
});
(8)Comparable和Comparator的区别:
java.lang.Comparable:在类定义的时候,可以实现好的接口,里面有compareTo这个方法需要实现。
java.util.Comparator:是挽救的比较接口,需要单独定义一个比较类,里面有compare比较方法。
使用集合生成随机数
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
public class Tgrade {
public static void main(String[] args) {
// Set<Integer> a= new HashSet<Integer>();
Set<Integer> a= new TreeSet<Integer>();//数据自然排序
//生成随机数
Random it = new Random();
while(a.size()<10){
int number= it.nextInt(20)+1;
a.add(number);
}
for(Integer w:a){
System.out.println(w);
}
}
}
5.3 泛型
本质是参数化类型,即将类型由原来的具体的类型参数化,然后在使用/调用的时传入具体的类型。这种参数类型可以用在类,方法和接口中,分别称为泛型类,泛型方法,泛型接口。
6.1泛型的使用方式
(1):泛型类
public class T泛型 {
public static void main(String[] args) {
Own泛型<String> g=new Own泛型<String>();
g.setT("文佳");
System.out.println(g.getT());
Own泛型<Integer> g1=new Own泛型<Integer>();
g1.setT(1);
System.out.println(g1.getT());
}
}
//自定义泛型类
class Own泛型 <T>{
private T t;
public void setT(T t) {
this.t = t;
}
public T getT() {
return t;
}
}
(2)泛型方法及泛型类的使用
public class 泛型 {
public static void main(String[] args) {
awc a = new awc();
a.show("q");
a.show(5);
System.out.println("*************");
awc泛型类<String> b=new awc泛型类<String>();
b.show("w");
awc泛型类<Integer> b1=new awc泛型类<Integer>();
b1.show(2);
System.out.println("*************");
awc泛型方法 c = new awc泛型方法();
c.show("j");
c.show(1);
}
}
//正常
class awc{
public void show(String a) {
System.out.println(a);
}
public void show(Integer a) {
System.out.println(a);
}
}
//泛型类
class awc泛型类<T>{
public void show(T a) {
System.out.println(a);
}
}
//泛型方法
class awc泛型方法 {
public <T> void show(T a) {
System.out.println(a);
}
}
(3)泛型类接口
public class 泛型接口 {
public static void main(String[] args) {
own1<String> a = new own1<String>();
a.show("jka");
own1<Integer> a2 = new own1<Integer>();
a2.show(12);
}
}
//泛型接口
interface own接口<K>{
default void show(K t){
System.out.println(t);
}
}
//该接口的实现类
class own1 <K>implements own接口<K>{
@Override
public void show(K t) {
System.out.println(t);
}
}
6.2类型通配符
import java.util.ArrayList;
import java.util.List;
public class 类型通配符 {
public static void main(String[] args) {
List<?> a=new ArrayList<Object>();
List<?> a1=new ArrayList<Number>();
List<?> a2=new ArrayList<Integer>();
// 通配上限
// List<? extends Number> a4=new ArrayList<Object>();Object为Number的父类
List<? extends Number> a4=new ArrayList<Number>();
List<? extends Number> a5=new ArrayList<Integer>();
// 通配下限
// List<? super Number> a6=new ArrayList<Integer>();Integer为Number的子类
List<? super Number> a6=new ArrayList<Number>();
List<? super Number> a7=new ArrayList<Object>();
}
}
6.3可变参数
public class 可变参数 {
public static void main(String[] args) {
System.out.println(sum(1));
System.out.println(sum(1,2));
}
//可变参数。a实际上是一个数组
public static int sum(int...a){
int num=0;
for(int i:a){
num+=num+i;
}
return num;
}
/*
public static int sum(int a){
return a;
}
public static int sum(int a,int b){
return a+b;
}*/
}
可变参数的使用
5.4 Map(双列)
5.3.1 Map集合概述及使用
import java.util.HashMap;
import java.util.Map;
public class Map集合 {
public static void main(String[] args) {
Map<String,String> a=new HashMap<String,String>();
//添加元素V put(K key, V value) 将指定的值与此映射中的指定键相关联。
a.put("q001","uj");
a.put("q002","u");
a.put("q002","i");//覆盖键对应的原值
System.out.println(a);
}
}
5.3.2Map常用方法及获取
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Map常用方法及获取功能 {
public static void main(String[] args) {
Map<String,String> a=new HashMap<String,String>();
//添加元素
a.put("11","1");
a.put("22","2");
System.out.println(a.get("11"));
Set<String> a1 = a.keySet();//a1为一个集合
for(String w:a1){
System.out.println(w);
}
System.out.println(a);
}
}
5.3.3Map集合的两种遍历方式
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Map集合的遍历 {
public static void main(String[] args) {
Map<String,String> a=new HashMap<String,String>();
a.put("q001","w");
a.put("q002","j");
a.put("q003","q");
//遍历方式(1)
Set<String> a1 = a.keySet();//先获取键的集合
for(String values:a1)
{
String s = a.get(values);//根据键对应值
System.out.println(s);
}
//遍历方式(2)
Set<Map.Entry<String, String>> a2 = a.entrySet();//获取所有键值对对象的集合·
for(Map.Entry<String, String> e:a2){
String key = e.getKey();//得到键
String value = e.getValue();//得到值
System.out.println(key+" ,"+value);
}
}
}
5.3.4ArrayList和HashMap的相互嵌套
import java.util.*;
public class ArrayList嵌套HashMap {
public static void main(String[] args) {
List<HashMap<String,String>> a=new ArrayList<HashMap<String,String>>();
HashMap<String,String> b=new HashMap<String,String>();
b.put("1","11");
b.put("孙策","大乔");
a.add(b);
HashMap<String,String> b1=new HashMap<String,String>();
b1.put("2","22");
b1.put("周瑜","小乔");
a.add(b1);
HashMap<String,String> b2=new HashMap<String,String>();
b2.put("3","33");
b2.put("刘备","孙尚香");
a.add(b2);
//遍历
for( HashMap<String,String> w:a){
Set<String> q = w.keySet();
for(String r:q){
String s = w.get(r);
System.out.println(r+","+s);
}
}
System.out.println(a);
}
}
import java.util.*;
public class HashMap嵌套ArrayList {
public static void main(String[] args) {
Map<String, ArrayList<String>> a=new HashMap<String, ArrayList<String>>();
ArrayList<String> b = new ArrayList<>();
b.add("01");
b.add("02");
ArrayList<String> b1 = new ArrayList<>();
b1.add("11");
b1.add("12");
ArrayList<String> b2 = new ArrayList<>();
b2.add("21");
b2.add("22");
a.put("m",b);
a.put("n",b1);
a.put("q",b2);
//遍历方式(1)
Set<String> q = a.keySet();
for(String w:q){
System.out.println(w);
ArrayList<String> values = a.get(w);
for(String d:values){
System.out.println("\t"+d);
}
}
System.out.println("********************");
//遍历方式(2)
Set<Map.Entry<String, ArrayList<String>>> e = a.entrySet();
for(Map.Entry<String, ArrayList<String>> o:e){
String key = o.getKey();
System.out.println(key);
ArrayList<String> value = o.getValue();
for(String d:value){
System.out.println("\t"+d);
}
}
}
}
5.5Collections的使用
import java.util.ArrayList;
import java.util.Collections;
//Collections是一个具体的类
public class Colletions的使用 {
public static void main(String[] args) {
ArrayList<Integer> a = new ArrayList<>();
a.add(10);
a.add(40);
a.add(20);
a.add(50);
a.add(30);
//升序排列
// Collections.sort(a);
//返转顺序
// Collections.reverse(a);
//默认的随机源随机排列指定的列表(斗地主洗牌等情况)
Collections.shuffle(a);
System.out.println(a);
}
}
注:Collections.sort();可以用于学生的排序,添加比较器。
即方法:static void sort(List list, Comparator<? super T> c)
(根据指定的比较器引起的顺序对指定的列表进行排序。)
import java.util.*;
//实现洗牌,发牌,看牌(牌是按升序排列)
//使用了HashMap(编号,牌)和ArrayList.(编号) 洗编号,来模拟随机发牌
public class 模拟斗地主2 {
public static void main(String[] args) {
HashMap<Integer, String> a = new HashMap<Integer, String>();
ArrayList<Integer> b = new ArrayList<>();
String[] colors = {"方块", "♣", "♥", "♠"};
String[] numbers = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
int w=0;
for(int i=0;i<colors.length;i++){
for(int j=0;j<numbers.length;j++){
String s = colors[i] + numbers[j];
a.put(w,s);
b.add(w);
w++;
}
}
a.put(52,"小王");
a.put(53,"大王");
b.add(w);
w++;
b.add(w);
Collections.shuffle(b);
TreeSet<Integer> m1 = new TreeSet<>();
TreeSet<Integer> m2 = new TreeSet<>();
TreeSet<Integer> m3= new TreeSet<>();
TreeSet<Integer> mn = new TreeSet<>();
for (int i = 0; i < b.size(); i++) {
if (i >=b.size() - 3) {
mn.add(b.get(i));
} else if (i % 3 == 0) {
m1.add(b.get(i));
} else if (i % 3 == 1) {
m2.add(b.get(i));
} else {
m3.add(b.get(i));
}
}
see("m1",m1,a);
see("m2",m2,a);
see("m3",m3,a);
see("mn",mn,a);
}
public static void see( String e,TreeSet<Integer> m, HashMap<Integer, String> a0){
System.out.print(e+"的牌为 ");
for(int k:m){
String s = a0.get(k);
System.out.print(s+" ");
}
System.out.println("\n");
}
}
5.6集合框架
1.为什么使用集合框架?
在我们的开发实践中,经常需要保存一些变长的数据集合,于是,我们需要一些能够动态增长长度的容器来保存我们的数据。
而我们需要对数据的保存的逻辑可能各种各样,于是就有了各种各样的数据结构。我们将数据结构在Java中实现,于是就有了我们的集合框架。
2.集合框架继承图
六.IO流
6.1File
6.1.1File类的概述和构造方法
import java.io.File;
/*File:文件和目录路径名的抽象表示。
其构造方法:
File(File parent, String child) 从父抽象路径名和子路径名字符串创建新的 File实例。
File(String pathname) 通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例。
File(String parent, String child) 从父路径名字符串和子路径名字符串创建新的 File实例。*/
public class File的概述 {
public static void main(String[] args) {
File a1 = new File("D\\a\\w.txt");
System.out.println(a1);
File a2 = new File("D\\a","w.txt");
System.out.println(a2);
File a3 = new File("D\\a");
File a4 = new File(a3,"w.txt");
System.out.println(a4);
}
}
6.1.2File类的创建功能
import java.io.File;
import java.io.IOException;
//public boolean createNewFile()不存在是创建一个该名的新空文件。并返回true
//下面两种类似
public class File类创建功能 {
public static void main(String[] args) throws IOException {
File a1 = new File("D:\\a\\e.txt");//IOException系统找不到指定的路径(a不存在)
// System.out.println(a1.createNewFile());
File a2 = new File("D:\\a");
System.out.println(a2.mkdir());
File a3 = new File("D:\\b\\e.txt");
System.out.println(a3.mkdirs());
File a4 = new File("e.txt");//创建在项目中
System.out.println(a4.createNewFile());
}
}
6.1.3File类的删除功能
import java.io.File;
import java.io.IOException;
public class File类删除功能 {
public static void main(String[] args) throws IOException {
//在当前模块目录下创建java.txt文件
File a1 = new File("java.txt");
System.out.println(a1.createNewFile());
System.out.println(a1.delete());//删除文件
System.out.println("************");
//在当前模块目录下创建itcast目录
File a2 = new File("itcast");
System.out.println(a2.mkdir());
System.out.println(a2.delete());
System.out.println("************");
//在当前模块目录下创建itcast目录,然后在该目录下创建java.txt文件
File a3= new File("itcast");
System.out.println(a3.mkdir());
File a4 = new File("itcast\\java.txt");
System.out.println(a4.createNewFile());
System.out.println(a4.delete());
System.out.println(a3.delete());
}
}
6.1.4File类判断和获取功能
import java.io.File;
import java.io.IOException;
public class File类判断和获取功能 {
public static void main(String[] args) throws IOException {
File a1 = new File("icast");
System.out.println(a1.mkdir());//创建目录
System.out.println(a1.isDirectory());//是否是目录
System.out.println(a1.isFile());//是否是文件
System.out.println(a1.exists());//测试抽象名称表示的File是否存在
File a2=new File("icast\\wen\\jia");
System.out.println(a2.getAbsolutePath());//返回绝对路径
System.out.println(a2.getPath());//返回相对路径
System.out.println(a2.getName());//文件或目录的名称
System.out.println("**********************************");
String[] e = a2.list();//名称字符串数组
for(String w:e){
System.out.println(w);
}
File[] r = a2.listFiles();//File对象数组
for(File t:r){
if(t.isFile())//可以加条件,判断是否为文件
System.out.println(t.getName());
}
}
}
6.1.5递归
遍历目录(通过递归)
import java.io.File;
//通过递归来遍历目录
public class 遍历目录 {
public static void main(String[] args) {
File a = new File("icast");
wen(a);
}
public static void wen(File e) {
File[] w = e.listFiles();
if (w != null) {
for (File r : w) {
if (r.isDirectory())
wen(r);
else
System.out.println(r.getAbsolutePath());
}
}
}
}
6.2字节流
6.2.1 IO流概述和分类
6.2.2字节流写数据
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-O6WXe1wr-1652095210453)(https://gitee.com/kang-zhijian/drawing-bed/raw/master/%E5%AD%97%E8%8A%82%E6%B5%81%E5%86%99%E6%95%B0%E6%8D%AE(2)].jpg)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OLmAHPC5-1652095210454)(https://gitee.com/kang-zhijian/drawing-bed/raw/master/%E5%AD%97%E8%8A%82%E6%B5%81%E5%86%99%E6%95%B0%E6%8D%AE(3)].jpg)
import java.io.FileOutputStream;
import java.io.IOException;
/*1.字节流写数据及三种输入方式
2.字节流写数据实现换行
3.字节流写数据实现追加写入
*/
public class 字节流写数据 {
public static void main(String[] args) throws IOException {
//1.创建字节输出流对象
FileOutputStream a = new FileOutputStream("wer.txt", true);//可以实现追加写入
//2.调用字节输出流对象的写数据方法(3种)
//2.1 void write(int b) 将指定的字节写入此文件输出流。
a.write(97);
//2.2 void write(byte[] b) 将 b.length字节从指定的字节数组写入此文件输出流。
byte[] bys = "abcde".getBytes();
a.write(bys);
//2.3 void write(byte[] b, int off, int len) 将 len字节从指定的字节数组开始,从偏移量 off开始写入此文件输出流。
a.write(bys,1,3);
//实现换行操作
for (int i = 0; i < 3; i++) {
a.write("hello".getBytes());
a.write("\n".getBytes());
}
//3.释放资源
a.close();
}
}
注:字节流写对象换行"\n" 对 windows也可以
6.2.3字节流读数据
(1)一次读取一个字节
import java.io.FileInputStream;
import java.io.IOException;
/*
1.一次读取一个字节
2.到达文件的结尾,则值为 -1 。
*/
public class 字节流读数据1 {
public static void main(String[] args) throws IOException {
FileInputStream a = new FileInputStream("wen.txt");
int i1 = a.read();
System.out.println((char) i1);//强制转换可以转为字符型
//优化读取
int by; //while 不能定义变量
while ((by = a.read()) != -1) {
//此处不使用 System.out.println();因为会导致默认换行
System.out.print((char) by);
}
a.close();
}
}
(2)一次读取一个字节数组
import java.io.FileInputStream;
import java.io.IOException;
/*
1.一次读一个字节数组数据
2. String(byte[] bytes, int offset, int length)
通过使用平台的默认字符集解码指定的字节子阵列来构造新的 String 。(自定义读取长度)
*/
public class 字节流读数据2 {
public static void main(String[] args) throws IOException {
FileInputStream a = new FileInputStream("wen.txt");
byte[] b = new byte[5];
int len = a.read(b); //实际读取的字符数
System.out.println(len);
System.out.println(new String(b));
System.out.println(new String(b, 0, 3));
//优化读取
int lent;
byte[] b1 = new byte[1024];//一般为1024及其整数倍
while ((lent = a.read(b1)) != -1) {
System.out.println(lent);
System.out.println(new String(b1));
}
a.close();
}
}
6.2.4字节缓冲流
import java.io.*;
//输入流未写
public class 字节缓冲流 {
public static void main(String[] args) throws IOException {
BufferedOutputStream a = new BufferedOutputStream(new FileOutputStream("jia.txt"));
//BufferedInputStream b = new BufferedInputStream(new FileInputStream("jia.txt"));
a.write("wenjiaqi".getBytes());
a.close();
}
}
6.2.5对数据的复制
import java.io.*;
public class 复制文本 {
public static void main(String[] args) throws IOException {
//创建输入输出流对象
FileInputStream a1 = new FileInputStream("wen.txt");
FileOutputStream a2 = new FileOutputStream("jia.txt");
//读数据
int b;
while ((b = a1.read()) != -1) {
a2.write(b);
}
a1.close();
a2.close();
}
}
import java.io.*;
public class 复制图片 {
public static void main(String[] args) throws IOException {
FileOutputStream a = new FileOutputStream("D:\\zzw\\mn.jpg");
FileInputStream b = new FileInputStream("D:\\zzq\\1.jpg");
int len;
byte[] v = new byte[1024];
while ((len=b.read(v))!=-1){
a.write(v);
}
a.close();
b.close();
}
}
import java.io.*;
/*
1.四种读写数据的方法
2.字节数组的大小也会影响耗时
*/
public class 复制视频 {
public static void main(String[] args) throws IOException {
//记录开始时间
long start = System.currentTimeMillis();
// method1();//共耗时:17248毫秒
// method2();//共耗时:31毫秒
// method3();//共耗时:83毫秒
// method4();//共耗时:12毫秒
long end = System.currentTimeMillis();
System.out.println("共耗时:"+(end-start)+"毫秒");
}
//基本字节流一次读一个字节
public static void method1() throws IOException {
FileOutputStream a = new FileOutputStream("D:\\zzw\\2.MP4");
FileInputStream b = new FileInputStream("D:\\zzq\\1.mp4");
int by;
while((by=b.read())!=-1){
a.write(by);
}
}
//基本字节流一次读一个字节数组
public static void method2() throws IOException {
FileOutputStream a = new FileOutputStream("D:\\zzw\\2.mp4");
FileInputStream b = new FileInputStream("D:\\zzq\\1.mp4");
int by;
byte[] w = new byte[1024];
while((by=b.read(w))!=-1){
a.write(w);
}
}
//缓冲字节流一次读取一个字节
public static void method3() throws IOException {
BufferedOutputStream a = new BufferedOutputStream(new FileOutputStream("D:\\zzw\\2.MP4"));
BufferedInputStream b = new BufferedInputStream(new FileInputStream("D:\\zzq\\1.mp4"));
int by;
//缓冲字节流一次读取一个字节数组
public static void method4() throws IOException {
BufferedOutputStream a = new BufferedOutputStream(new FileOutputStream("D:\\zzw\\2.mp4"));
BufferedInputStream b = new BufferdzafdvbedInputStream(new FileInputStream("D:\\zzq\\1.mp4"));
int by;
byte[] w = new byte[1024];
while((by=b.read(w))!=-1){
a.write(w);
}
}
6.3字符流
6.3.1字符串和字符流的编码解码
字符串的编码解码
import java.util.Arrays;
/*
中文的第一个字节都是负数
*/
public class 字符串的编码解码 {
public static void main(String[] args) {
String a="中国";
//编码
byte[] bys = a.getBytes();//[-28, -72, -83, -27, -101, -67]
//解码
String s = new String(bys);
System.out.println(Arrays.toString(bys));
System.out.println(s);
}
} while((by=b.read())!=-1){
a.write(by);
}
}
字符流的编码解码
import java.io.*;
/*
1.OutputStreamWriter是从字符流到字节流的桥梁:
使用指定的charset将写入的字符编码为字节。 它使用的字符集可以由名称指定,也可以被明确指定,或者可以接受平台的默认字符集。
2.InputStreamReader是从字节流到字符流的桥梁:
它读取字节,并使用指定的charset将其解码为字符。 它使用的字符集可以由名称指定,也可以被明确指定,或者可以接受平台的默认字符集。
*/
public class 字符流的编码解码 {
public static void main(String[] args) throws IOException {
OutputStreamWriter b = new OutputStreamWriter(new FileOutputStream("wen.txt"));
InputStreamReader c = new InputStreamReader(new FileInputStream("jia.txt"));
b.write("中国");
int le;
while((le=c.read())!=-1){
System.out.println((char)le);
}
b.close();
c.close();
}
}
6.3.2字符流写数据
五种方式:
import java.io.*;
public class 字符流写数据 {
public static void main(String[] args) throws IOException {
OutputStreamWriter b = new OutputStreamWriter(new FileOutputStream("wen.txt"));
//1.写一个字符
// b.write(55);
b.flush();//刷新流
char[] a= {'a','c','v','v'};
//2.写一个字符数组
// b.write(a);
//3.写一个字符数组一部分
// b.write(a,0,3);
//4.写一个字符串
// b.write("abcd");
//5.写一个字符串一部分
b.write("abcd",0,3);
b.close();//关闭流,先刷新。
}
}
6.3.3字符流读数据
两种方式:
import java.io.*;
public class 字符流读数据 {
public static void main(String[] args) throws IOException {
InputStreamReader a = new InputStreamReader(new FileInputStream("wen.txt"));
//1.一次读一个字符
int e;
while((e=a.read())!=-1){
System.out.print((char)e);
}
//2.一次读一个字符数组
int e2;
char[] d = new char[1024];
while((e2=a.read(d))!=-1){
System.out.println(new String(d));
}
}
}
6.3.4字符缓冲流
import java.io.*;
public class 字符缓冲流 {
public static void main(String[] args) throws IOException {
/* BufferedWriter d = new BufferedWriter(new FileWriter("wen.txt"));
d.write("hello\n");
d.write("world");*/
BufferedReader c = new BufferedReader(new FileReader("wen.txt"));
//一次读取一个字节数组
int le;
char[] er = new char[1024];
while((le=c.read(er))!=-1){
System.out.print(new String(er,0,le));
}
c.close();
}
其特有功能:
import java.io.*;
public class 字符缓冲流特有功能 {
public static void main(String[] args) throws IOException {
/* 1. 写一行分隔符
BufferedWriter a = new BufferedWriter(new FileWriter("wen.txt"));
for (int i = 0; i < 6; i++) {
a.write("hello"+i);
// a.write("\n");
a.newLine();
a.flush();
}
a.close();
*/
//读取一行文字
BufferedReader b = new BufferedReader(new FileReader("wen.txt"));
String s = null;
while((s=b.readLine())!=null){
System.out.println(s);
}
b.close();
}
}
6.3.5对数据的复制
import java.io.*;
//字符流特有功能4.0
public class 复制Java文件4 {
public static void main(String[] args) throws IOException {
BufferedReader a = new BufferedReader(new FileReader("k.java"));
BufferedWriter b = new BufferedWriter( new FileWriter("l.java"));
String s = null;
while((s=a.readLine())!=null){ //readLine不包括换行符
b.write(s);
b.newLine();
b.flush();
}
a.close();
b.close();
}
}
/*
import java.io.*;
//3.0
public class 复制Java文件3 {
public static void main(String[] args) throws IOException {
BufferedReader a = new BufferedReader(new FileReader("k.java"));
BufferedWriter b = new BufferedWriter( new FileWriter("l.java"));
//2.0
//是InputStreamReader和OutputStreamWriter的子类。目的为了书写方便
FileWriter a = new FileWriter("k.java");
FileReader b = new FileReader("l.java");
//1.0
OutputStreamWriter a = new OutputStreamWriter(new FileOutputStream("l.java"));
InputStreamReader b = new InputStreamReader(new FileInputStream("k.java"));
int le;
char[] cv = new char[1024];
while((le=a.read(cv))!=-1){
b.write(cv,0,le);
}
a.close();
b.close();
}
}
*/
6.4 IO流小结
注:涉及到编码问题还必须使用input…和output…
处理异常:
import java.io.*;
import java.util.Scanner;
public class 键盘输入 {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
String s = a.nextLine();
byte[] by = s.getBytes();
//对于异常的处理不需要关闭流。jdk7的特性。
try( BufferedOutputStream b= new BufferedOutputStream(new FileOutputStream("D:\\zzq\\1.txt"))) {
b.write(by);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("写入文件成功!");
try(BufferedInputStream c = new BufferedInputStream(new FileInputStream("D:\\zzq\\1.txt"))) {
int len;
byte[] by1 = new byte[1024];
System.out.println("从文件中读取的内容为:");
while((len=c.read(by1))!=-1){
System.out.print(new String(by1));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
6.5特殊操作流
6.5.1标准输入输出流:
(1):标准输入流
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class 标准输入流 {
public static void main(String[] args) throws IOException {
/* //标准输入流
InputStream in = System.in;
int a;
while ((a=in.read())!=-1){
System.out.println((char)a);
}
//用转换流将字节流转换为字符流
InputStreamReader b = new InputStreamReader(in);
//用缓冲流实现一次读取一行
BufferedReader c = new BufferedReader(b);
*/
BufferedReader d = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入一个字符串");
String s = d.readLine();
System.out.println("输入的字符串为"+s);
System.out.println("请输入一个整数:");
int i = Integer.parseInt(d.readLine());
System.out.println("输入的整数为"+i);
//因为自己实现键盘录入太麻烦,所以Java提供了Scanner类,来实现键盘的录入。
}
}
(2):标准输出流
import java.io.PrintStream;
public class 标准输出流 {
public static void main(String[] args) {
PrintStream out = System.out;
out.println("100");
out.println("Hello");
System.out.println("100");
System.out.println("Hello");
}
}
6.5.2 打印流
(1):字节打印流
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class 字节打印流 {
public static void main(String[] args) throws FileNotFoundException {
PrintStream p = new PrintStream("wen.txt");
p.write(100);
p.println();
p.println(100);
}
}
(2):字符打印流
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class 字符打印流 {
public static void main(String[] args) throws IOException {
/* PrintWriter p = new PrintWriter("wen.txt");
p.write("hello");
p.write("\r"); //换行
p.flush(); //刷新缓冲区
p.write("wen");
p.write("\r");
p.flush();*/
PrintWriter p1 = new PrintWriter(new FileWriter("wen.txt"), true);
p1.println("hello");
p1.println("wenjiaqi");
}
}
6.5.3 序列流和反序列流
import java.io.*;
//对象序列化流即输出流写入到文件中
public class 对象序列化流和反序列化流 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectOutputStream a = new ObjectOutputStream(new FileOutputStream("wen.txt"));
ObjectInputStream b = new ObjectInputStream(new FileInputStream("wen.txt"));
Student2 s = new Student2("温",18);
a.writeObject(s);
Object o = b.readObject();
Student2 o1 = (Student2) o;
System.out.println("姓名:"+o1.getName()+"年龄"+o1.getAge());
a.close();
b.close();
}
}
七.多线程
7.1 进程和线程
7.2多线程的实现方法1
/*
1.线程的实现方式1
2.设置和获取线程的名称
*/
//开启线程不一定立即执行,由CPU调度执行
public class Tthread extends Thread{
//添加有参构造方法。
public Tthread(){
}
public Tthread(String name){
super(name);
}
//线程入口点
@Override
public void run() {
for (int i=0;i<100;i++)
System.out.println("你真漂亮"+i+getName());
}
public static void main(String[] args) {
//创建线程对象
Tthread a=new Tthread();
Tthread a1=new Tthread();
// Tthread a2=new Tthread("温嘉琪");
a1.setName("温");
a.setName("嘉琪");
a.start();//调用start()开启线程
a1.start();
/* a.run();//普通的方法调用
for(int i=0;i<100;i++)
System.out.println("温嘉琪你真漂亮"+i);*/
}
}
7.3线程优先级
public class 线程优先级 {
public static void main(String[] args) {
Tthread1 a0=new Tthread1("温");
Tthread1 a1=new Tthread1("嘉");
Tthread1 a2=new Tthread1("琪");
//优先级从1-10
a0.setPriority(10);
a1.setPriority(1);
a2.setPriority(5);
System.out.println(Thread.MAX_PRIORITY);//最大
System.out.println(Thread.MIN_PRIORITY);//最小
System.out.println(Thread.NORM_PRIORITY);//默认
}
}
class Tthread1 extends Thread{
public Tthread1(String name){
super(name);
}
//线程入口点
@Override
public void run() {
for (int i=0;i<100;i++)
System.out.println("你真漂亮"+i+getName());
}
}
7.4线程的控制
// 1.static void sleep(long millis, int nanos) 导致正在执行的线程以指定的毫秒数加上指定的纳秒数来暂停(临时停止执行)
public class 线程的控制1 {
public static void main(String[] args) {
Tthread2 a0 = new Tthread2("温");
Tthread2 a1 = new Tthread2("嘉");
Tthread2 a2 = new Tthread2("琪");
a0.start();
a1.start();
a2.start();
}
}
class Tthread2 extends Thread{
public Tthread2(String name){
super(name);
}
//线程入口点
@Override
public void run() {
for (int i=0;i<100;i++)
System.out.println("你真漂亮"+i+getName());
//使线程休眠
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 2. void join() 等待这个线程死亡
public class 线程控制2 {
public static void main(String[] args) {
Tthread3 a0 = new Tthread3("温");
Tthread3 a1 = new Tthread3("嘉");
Tthread3 a2 = new Tthread3("琪");
a0.start();
try {
a0.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
a1.start();
a2.start();
}
}
class Tthread3 extends Thread{
public Tthread3(String name){
super(name);
}
//线程入口点
@Override
public void run() {
for (int i=0;i<100;i++)
System.out.println("你真漂亮"+i+getName());
}
}
// 3.void setDaemon(boolean on) 将此线程标记为 daemon线程或用户线程。
public class 线程控制3 {
public static void main(String[] args) {
Tthread4 a0 = new Tthread4("温");
Tthread4 a1 = new Tthread4("嘉");
// Tthread4 a2 = new Tthread4("琪");
a0.setDaemon(true);
a1.setDaemon(true);
a0.start();
a1.start();
// a2.start();
Thread.currentThread().setName("琪");
for (int i=0;i<10;i++)
System.out.println("你真漂亮"+i+Thread.currentThread().getName());
}
}
class Tthread4 extends Thread{
public Tthread4(String name){
super(name);
}
//线程入口点
@Override
public void run() {
for (int i=0;i<100;i++)
System.out.println("你真漂亮"+i+getName());
}
}
7.5线程生命周期
7.6多线程的实现方法2
public class 多线程实现方法2 {
public static void main(String[] args) {
MyRun my = new MyRun();
/* Thread t1 = new Thread(my);
Thread t2 = new Thread(my);*/
Thread t1 = new Thread(my,"温");
Thread t2 = new Thread(my,"嘉");
t1.start();
t2.start();
}
}
class MyRun implements Runnable{
@Override
public void run() {
for(int i=0;i<100;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
7.7卖票案例
同步代码块
//同步代码块解决卖票出现的问题
public class 卖票 {
public static void main(String[] args) {
Cticket c1 = new Cticket();
Thread t1 = new Thread(c1,"1号");
Thread t2 = new Thread(c1,"2号");
Thread t3 = new Thread(c1,"3号");
t1.start();
t2.start();
t3.start();
}
}
class Cticket implements Runnable {
private int tickets = 100;
private Object oj = new Object();
@Override
public void run() {
while (true) {
synchronized (oj) {
if (tickets > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "窗口出卖:第" + tickets + "张票");
tickets--;
}
}
}
}
}
2同步方法
public class 卖票同步方法 {
public static void main(String[] args) {
Cticket1 c1 = new Cticket1();
Thread t1 = new Thread(c1, "1号");
Thread t2 = new Thread(c1, "2号");
Thread t3 = new Thread(c1, "3号");
t1.start();
t2.start();
t3.start();
}
}
class Cticket1 implements Runnable {
private int tickets = 100;
private int x = 0;
private Object oj = new Object();
@Override
public void run() {
while (true) {
if (x % 2 == 0) {
// synchronized (oj) {
synchronized (this) {
if (tickets > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "窗口出卖:第" + tickets + "张票");
tickets--;
}
}
} else {
sellTicket();
}
}
}
private synchronized void sellTicket() {
if (tickets > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "窗口出卖:第" + tickets + "张票");
tickets--;
}
}
}
7.8线程安全的类
7.9 Lock锁
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Lock锁 {
public static void main(String[] args) {
Cticket3 c1 = new Cticket3();
Thread t1 = new Thread(c1, "1号");
Thread t2 = new Thread(c1, "2号");
Thread t3 = new Thread(c1, "3号");
t1.start();
t2.start();
t3.start();
}
}
class Cticket3 implements Runnable {
private int tickets = 100;
private Lock c=new ReentrantLock();
//try结构,防止Lock锁住的内容出错,从而无法解锁。
@Override
public void run() {
while (true) {
try{
c.lock();
if (tickets > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "窗口出卖:第" + tickets + "张票");
tickets--;
}
}finally {
c.unlock();
}
}
}
}
7.10 生产者和消费者
八.网络编程
8.1.网络编程概述
8.2 . 网络编程三要素
8.3.IP地址
8.4 InetAddress 的使用
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IntAddness的使用 {
public static void main(String[] args) throws UnknownHostException {
// static InetAddress getByName(String host) 确定主机名称的IP地址。
// InetAddress a= InetAddress.getByName("LAPTOP-RQVPDLSK");
InetAddress a= InetAddress.getByName("10.62.48.202");
// String getHostName() 获取此IP地址的主机名。
String hostName = a.getHostName();
// String getHostAddress() 返回文本显示中的IP地址字符串。
String hostAddress = a.getHostAddress();
System.out.println(hostName);
System.out.println(hostAddress);
}
}
8.5 端口和协议
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDP发送数据 {
public static void main(String[] args) throws IOException {
//1.创建发送端对象DatagramSocket
DatagramSocket a=new DatagramSocket();
//2.创建数据,并把数据打包
// DatagramPacket(byte[] buf, int length, InetAddress address, int port)
// 构造一个数据包,发送长度为 length的数据包到指定主机上的指定端口号。
byte [] by="你好,好想你还在啊!".getBytes();
/*
* int length=by.length;
* InetAddress ad=InetAddress.getByName("10.62.48.202");
* int port=10086;
* DatagramPacket dp=new DatagramPacket(by, length, ad, port);
*/
DatagramPacket dp=new DatagramPacket(by, by.length, InetAddress.getByName("10.62.48.202"), 10086);
//3.调用DatagramSocket对象发送数据
//void send(DatagramPacket p) 从此套接字发送数据报包。
a.send(dp);
//4.关闭发送端
a.close();
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDP接收数据 {
public static void main(String[] args) throws IOException {
//1.创建接收端对象
DatagramSocket a=new DatagramSocket(10086);
//2.创建数据包接收数据
byte[] by = new byte[1024];
int length= by.length;
DatagramPacket dp = new DatagramPacket( by,length);
//3.调用方法接收数据
a.receive(dp);
//4.解析数据包,并把数据输出在控制台上
/* byte[] datas = dp.getData();
int len=dp.getLength();
String s = new String(datas,0,len);
System.out.println("数据为:"+s);
*/
System.out.println("数据为:"+new String(dp.getData(),0,dp.getLength()));
//5.关闭接收端
a.close();
}
}
UDP练习:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
public class UDP练习sent {
public static void main(String[] args) throws IOException {
DatagramSocket s = new DatagramSocket();
// DatagramPacket(byte buf[], int length,InetAddress address, int port)
System.out.println("请您输入数据:");
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
String line;
while((line=b.readLine())!=null){
if(line.equals("886")){
break;
}else{
byte[] by = line.getBytes();
DatagramPacket dp = new DatagramPacket(by,by.length,InetAddress.getByName("10.62.48.202"),10087);
s.send(dp);
}
}
s.close();
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDP练习receive {
public static void main(String[] args) throws IOException {
DatagramSocket d = new DatagramSocket(10087);
// public DatagramPacket(byte buf[], int length)
while(true) {
byte[] by = new byte[1024];
DatagramPacket dp = new DatagramPacket(by, by.length);
d.receive(dp);
byte[] data = dp.getData();
int len = dp.getLength();
System.out.println("数据为:" + new String(data, 0, len));
}
}
}
8.6
ecplise 的使用
1 :ctrl + 1 +回车 补全左侧代码
2: main +alt +/ 生成主方法
3:生成输出语句:输入"syso",按ALT+/,然后回车
4:代码自动对齐:Ctrl+Shift+F
ocket a=new DatagramSocket();
//2.创建数据,并把数据打包
// DatagramPacket(byte[] buf, int length, InetAddress address, int port)
// 构造一个数据包,发送长度为 length的数据包到指定主机上的指定端口号。
byte [] by="你好,好想你还在啊!".getBytes();
/*
* int length=by.length;
* InetAddress ad=InetAddress.getByName("10.62.48.202");
* int port=10086;
* DatagramPacket dp=new DatagramPacket(by, length, ad, port);
*/
DatagramPacket dp=new DatagramPacket(by, by.length, InetAddress.getByName("10.62.48.202"), 10086);
//3.调用DatagramSocket对象发送数据
//void send(DatagramPacket p) 从此套接字发送数据报包。
a.send(dp);
//4.关闭发送端
a.close();
}
}
```java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDP接收数据 {
public static void main(String[] args) throws IOException {
//1.创建接收端对象
DatagramSocket a=new DatagramSocket(10086);
//2.创建数据包接收数据
byte[] by = new byte[1024];
int length= by.length;
DatagramPacket dp = new DatagramPacket( by,length);
//3.调用方法接收数据
a.receive(dp);
//4.解析数据包,并把数据输出在控制台上
/* byte[] datas = dp.getData();
int len=dp.getLength();
String s = new String(datas,0,len);
System.out.println("数据为:"+s);
*/
System.out.println("数据为:"+new String(dp.getData(),0,dp.getLength()));
//5.关闭接收端
a.close();
}
}
UDP练习:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
public class UDP练习sent {
public static void main(String[] args) throws IOException {
DatagramSocket s = new DatagramSocket();
// DatagramPacket(byte buf[], int length,InetAddress address, int port)
System.out.println("请您输入数据:");
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
String line;
while((line=b.readLine())!=null){
if(line.equals("886")){
break;
}else{
byte[] by = line.getBytes();
DatagramPacket dp = new DatagramPacket(by,by.length,InetAddress.getByName("10.62.48.202"),10087);
s.send(dp);
}
}
s.close();
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDP练习receive {
public static void main(String[] args) throws IOException {
DatagramSocket d = new DatagramSocket(10087);
// public DatagramPacket(byte buf[], int length)
while(true) {
byte[] by = new byte[1024];
DatagramPacket dp = new DatagramPacket(by, by.length);
d.receive(dp);
byte[] data = dp.getData();
int len = dp.getLength();
System.out.println("数据为:" + new String(data, 0, len));
}
}
}
8.6
ecplise 的使用
1 :ctrl + 1 +回车 补全左侧代码
2: main +alt +/ 生成主方法
3:生成输出语句:输入"syso",按ALT+/,然后回车
4:代码自动对齐:Ctrl+Shift+F