int i = 123;
double j = i;
double j = Double.valueOf(i);
double i = 123.88;
int j = (int) i;
Double doubleObject = new Double(i); //或者Double object = i; 自动装箱机制
int j = doubleObject.intValue();
Integer num = new Integer(0);
Integer num = new Integer(0);
int num1 = num.intValue();
Integer num = 1; //自动装箱,自动装箱使用的是Integer.valueOf(1)而不是new Integer(1)
int num1 = num; //自动拆箱
public boolean equals(Object obj) {
if(obj instance of Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
public boolean equals(Object obj) {
return (this == obj);
}
public Mytime {
private int year;
private int month;
private int day;
public Mytime() {}
public Mytime(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Mytime)) return false;
if (this == obj) return true;
Mytime t = (Mytime)obj;
return (this.year == t.year && this.month == t.month && this.day == t.day);
return false;
}
}
interface MyMath {
public static final double PI = 3.1415926;
//接口中的常量的public static final可以省略
public abstract int sum(int a, int b);
//定义抽象方法时public abstract可以省略
}
public class Test01 {
public static void main (String[] args) {
//多态
MyMath mm = new MyMathImpl();
int result1 = mm.sum(10, 20);
int result2 = mm.sub(20, 10);
System.out.println(result1 + result2);
}
}
interface MyMath {
double PI = 3.1415926;
int sum(int a, int b);
int sub(int a, int b);
}
class MyMathImpl implements MyMath {
//不能省略public,重写父类的方法不能权限更低,接口中都是public方法
public int sum(int a, int b) {
return a + b;
}
public int sub(int a, int b) {
return a - b;
}
}
public class Test01 {
public static void main(String[] args) {
//多态 表面Animal没用
Flyable f = new Cat();
f.fly();
Flyable f2 = new Pig();
f2.fly();
Flyable f3 = new Fish();
f3.fly();
}
}
class Animal {
}
interface Flyable {
void fly();
}
class Cat extends Animal implements Flyable {
public void fly() {
System.out.println("飞猫起飞");
}
}
class Snake extends Animal {
}
//想飞翔就插翅膀这个接口
class Pig extends Animal implements Flyable {
public void fly() {
System.out.println("我是会飞的猪");
}
}
class Fish implements Flyable {
public void fly() {
System.out.println("我是飞鱼");
}
}
public static void main(String[] args) {
A a = new D();
B b = new D();
C c = new D();
/*
向下转型B和A没有继承关系也可以转,编译没问题,但是运行出错,记住就行
B b2 = (B)a;
b.m2();
*/
}
if (a instanceof D) {
D d = (D)a;
d.m2();
}
}
interface A {
void m1();
}
interface B {
void m2();
}
interface C {
void m3();
}
class D implements A, B, C {
//类实现接口需要重写接口中的抽象方法,public不能省略
public void m1(){}
public void m2(){}
public void m3(){}
}
pulbic class Master {
public void feed(Dog d) {}
public void feed(Cat c) {}
//如果需要其他宠物此时就需要再加一个方法(修改代码),扩展力太差,违背OCP原则:对扩展开放,对修改关闭
}
------------------------
public class Master {
public void feed (Animal a) {}
//面向Animal父类编程,父类比子类抽象,所以我们叫面向抽象编程,不要面向具体编程,提高程序扩展力
}
public class Test {
public static void main(String[] args) {
//创建厨师对象,如果之后需要换厨师,只需要该test类中的程序,其他不需要改,因为customer中属性使用的是接口FoodMenu
FoodMenu cooker1 = new ChinaCooker();
//创建顾客对象
Customer customer = new Customer(cooker1); //传入cooker1防止出现空指针异常
//顾客点菜
customer.order();
}
}
//顾客类,顾客has a FoodMenu
public class Customer{
private FoodMenu foodMenu; //封装好习惯
public Customer() {}
public Customer(FoodMenu fooMenu) {
this.foodMenu = foodMenu;
}
// setter getter
public void setFoodMenu(FoodMenu foodMenu) {
this.foodMenu = foodMenu;
}
public FoodMenu getFoodMenu() {
return foodMenu;
}
public void order() {
FoodMenu fm = this.getFoodMenu();
fm.shizichaodan();
fm.mayishangshu();
}
}
public interface FoodMenu {
void shizichaodan(){}
void mayishangshu(){}
}
//中餐厨师,实现餐单上的菜,厨师是接口的实现者
public class ChinaCooker implements FoodMenu{
public void shizichaodan() {
Sytstem.out.println("中餐师傅做的柿子炒蛋");
}
public void shizichaodan() {
Sytstem.out.println("中餐师傅做的蚂蚁上树");
}
}
public class AmercaCooker implements FoodMenu{
public void shizichaodan() {
Sytstem.out.println("西餐师傅做的柿子炒蛋");
}
public void mayishangshu() {
Sytstem.out.println("西餐师傅做的蚂蚁上树");
}
}
list.add(100); // 自动装箱Integer
boolean add(Object a);
int size();
void clear();
boolean contains(Object a);
boolean remove(Object a);
boolean isEmpty();
Object[] toArray(); // 调用这个方法把集合转成数组
Iterator it = c.iterator();
boolean hasNext() // 如果仍有元素可以迭代,则返回true
(2)Object next() // 返回迭代器的下一个元素
public class GenericTest01 {
public static void main(String[] args) {
List<Animal> mylist = new ArrayList<Animal>();
Cat c = new Cat();
Bird b = new Bird();
mylist.add(c);
mylist.add(b);
// 加上泛型表示迭代器迭代的是Animal类型
Iterator<Animal> it = mylist.iterator();
while (it.hasNext()) {
// 使用泛型之后,每次迭代返回的数据都是Animal类型
Animal a = it.next();
if (a instanceof Cat) {
Cat c2 = (Cat) a;
c2.catchMouse();;
}
a.move();
}
}
}
class Animal {
public void move() {
System.out.println("move!");
}
}
class Cat extends Animal {
public void catchMouse() {
System.out.println("catch mouse!");
}
}
class Bird extends Animal {
public void fly() {
System.out.println("flying!");
}
}
public class GenericTest02 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("http://www.baidu.com");
list.add("http://www.jingdong.com");
list.add("http://www.taobao.com");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
String newString = s.substring(7);
System.out.println(newString);
}
}
}
public class GenericTest03<St> {
public void doSome(St s) {
System.out.println(s);
}
public static void main(String[] args) {
GenericTest03<String> s = new GenericTest03<>();
s.doSome("abs");
}
}
Class.forName(完整包名字符串);
getClass()
方法public class ReflectTest01 {
public static void main(String[] args) {
// c1代表String.class文件,或者说c1代表String类型
Class c1 = null;
try {
c1 = Class.forName("java.lang.String");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String s = "abc";
Class c2 = s.getClass();
System.out.println(c1 == c2);
Class c3 = String.class;
System.out.println(c2 == c3);
}
}
public class ReflectTest02 {
public static void main(String[] args) {
User s1 = new User();
System.out.println(s1);
Class s2 = null;
Object c = null;
try {
s2 = Class.forName("bean.User");
c = s2.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} finally {
System.out.println(c);
}
}
}
public class ReflectTest03 {
public static void main(String[] args) throws Exception {
// 通过IO流读取ClassInfo.properties文件
FileReader reader = new FileReader("D:/Project/src/ClassInfo.properties");
// 创建属性类对象Map
Properties pro = new Properties(); // key和value都是String
// 加载
pro.load(reader);
// 关闭流
reader.close();
// 通过key获取value
String className = pro.getProperty("className");
System.out.println(className);
//通过反射机制创建对象
Class c = Class.forName(className);
Object o = c.newInstance();
System.out.println(o);
}
}
public class ReflectTest04 {
public static void main(String[] args) {
try {
Class c = Class.forName("reflect.myClass");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
class myClass {
static {
// 静态代码块在类加载的时候执行,并且只执行一次
System.out.println("静态代码块执行!");
}
}
Thread.currentThread().getContextClassLoader().getResource("").getPath();
public class AboutPath {
public static void main(String[] args) throws Exception {
// Thread.currentThread() 当前线程对象
// getContextClassLoader() 是线程对象的方法,可以获取当前线程的类加载器对象
// getResource("") 是类加载器对象的方法,默认从类的根路径下加载资源
String path = Thread.currentThread().getContextClassLoader().getResource("ClassInfo.properties").getPath();
System.out.println(path);
String path2 = Thread.currentThread().getContextClassLoader().getResource("reflect/ReflectTest01.class").getPath();
System.out.println(path2);
}
}
public class IoPropertiesTest {
public static void main(String[] args) throws Exception {
// 通过类路径文件获取绝对路径
// String path = Thread.currentThread().getContextClassLoader().getResource("ClassInfo.properties").getPath();
// FileReader reader = new FileReader(path);
// 直接以流的形式返回
InputStream reader = Thread.currentThread().getContextClassLoader().getResourceAsStream("ClassInfo.properties");
Properties pro = new Properties();
pro.load(reader);
reader.close();
String className = pro.getProperty("className");
System.out.println(className);
}
}
public class ResourceBundleTest {
public static void main(String[] args) {
ResourceBundle bundle = ResourceBundle.getBundle("ClassInfo");
String className = bundle.getString("className");
System.out.println(className);
}
}
public class Student {
public int no;
private String name;
protected int age;
boolean sex;
public static final double MATH_PI = 3.1415926;
}
public class ReflectTest05 {
public static void main(String[] args) throws Exception {
Class c = Class.forName("bean.Student");
// 获取类中所有public修饰的field
String fullName = c.getName();
System.out.println("全类名:" + " " + fullName);
String simpleName = c.getSimpleName();
System.out.println("简类名:" + " " + simpleName);
System.out.println("====================");
// 只能获取public修饰的field
Field[] fields = c.getFields();
System.out.println(fields.length);
Field f = fields[0];
System.out.println(f.getName());
System.out.println("====================");
// 获取所有field名字
Field[] fs = c.getDeclaredFields();
for(Field fd : fs) {
System.out.println(fd.getName());
}
System.out.println("====================");
// 获取所有field类型
for(Field fd : fs) {
Class fType = fd.getType();
String typeName = fType.getName();
System.out.println(typeName);
}
System.out.println("====================");
// 获取所有field修饰符
for(Field fd : fs) {
// 返回的修饰符是一个数字,该数字是这个修饰符的代号!
int fdModifier = fd.getModifiers();
System.out.println(fdModifier);
// 将代号转为对应的修饰符名称
String modifier = Modifier.toString(fdModifier);
System.out.println(modifier);
}
}
}
public class ReflectTest06 {
public static void main(String[] args) throws Exception {
StringBuilder sb = new StringBuilder();
Class StudentClass = Class.forName("bean.Student");
sb.append(Modifier.toString(StudentClass.getModifiers()) + " class " + StudentClass.getSimpleName() + " {\n");
Field[] fields = StudentClass.getDeclaredFields();
for(Field field : fields) {
sb.append("\t");
sb.append(Modifier.toString(field.getModifiers()) + " " + field.getType().getName() + " " + field.getName());
sb.append(";");
sb.append("\n");
}
sb.append("}");
System.out.println(sb.toString());
}
}
public class ReflectTest07 {
public static void main(String[] args) throws Exception {
Student sd = new Student();
sd.no = 123;
System.out.println(sd.no);
InputStream reader = Thread.currentThread().getContextClassLoader().getResourceAsStream("ClassInfo.properties");
Properties pro = new Properties();
pro.load(reader);;
reader.close();
String className = pro.getProperty("className");
String filedName = pro.getProperty("fieldName");
String noValue = pro.getProperty("noValue");
Class studentClass = Class.forName(className);
Object obj = studentClass.newInstance();
// Student s = (Student) obj;
Field noField = studentClass.getDeclaredField(filedName);
System.out.println(noField.get(obj));
noField.set(obj, Integer.valueOf(noValue));
System.out.println(noField.get(obj));
}
}
Field nameField = studentClass.getDeclaredField(fieldName1);
// 反射缺点:打破封装
nameField.setAccessible(true);
nameField.set(obj, "jack");
System.out.println(nameField.get(obj));
public class ArgsTest {
public static void main(String[] args) {
test();
test(1, 2);
test(1, 2, 3, 4, 5);
test1(2, "a","b", "c");
test1(2, "a","b", "c", "def");
// 直接传一个数组
String[] array = {"abc", "def", "ghi"};
test1(10, array);
}
public static void test(int... args) {
System.out.println("可变长度参数方法执行");
}
public static void test1(int a, String... args) {
for(String arg : args) {
System.out.println(arg);
}
System.out.println("双类型参数方法执行");
}
}
public class ReflectTest08 {
public static void main(String[] args) throws Exception {
Class log = Class.forName("service.UserService");
Method[] methods = log.getDeclaredMethods();
for (Method method : methods) {
// 获取method的修饰符
System.out.println(Modifier.toString(method.getModifiers()));
// 获取method类型
Class type = method.getReturnType();
String typeName = type.getName();
System.out.println(typeName);
// 获取method名字
System.out.println(method.getName());
// 获取method参数列表
Class[] parameterTypes = method.getParameterTypes();
for(Class parameterType : parameterTypes) {
System.out.println(parameterType.getName());
}
}
}
}
public class UserService {
/**
* 登录方法
* @param name 用户名
* @param password 密码
* @return 返回true登陆成功,false登录失败
*/
public boolean login(String name, String password) {
return "admin".equals(name) && "123".equals(password);
}
/**
* 退出的方法
*/
public void logout() {
System.out.println("系统安全退出");
}
}
public class ReflectTest09 {
public static void main(String[] args) throws Exception {
Class service = Class.forName("service.UserService");
StringBuilder sb = new StringBuilder();
sb.append(Modifier.toString(service.getModifiers()) + " class " + service.getSimpleName());
sb.append(" {\n");
Method[] methods = service.getDeclaredMethods();
for (Method method : methods) {
sb.append("\t");
sb.append(Modifier.toString(method.getModifiers()) + " " + method.getReturnType().getSimpleName() + " " + method.getName());
sb.append("(");
Class[] parameterTypes = method.getParameterTypes();
for (Class parameterType : parameterTypes) {
sb.append(parameterType.getSimpleName());
sb.append(",");
}
// 防止无参方法丢失括号,需进行判断
if (sb.charAt(sb.length() - 1) == ',') {
sb.deleteCharAt(sb.length() - 1);
}
sb.append("){}");
sb.append("\n");
}
sb.append("}");
System.out.println(sb);
}
}
public class ReflectTest10 {
public static void main(String[] args) throws Exception {
Class c = Class.forName("service.UserService");
Object obj = c.newInstance();
Method method = c.getDeclaredMethod("login", String.class, String.class);
Object retValue = method.invoke(obj, "admin", "123");
System.out.println(retValue);
}
}
public class Vip {
int no;
String name;
String birth;
boolean sex;
public Vip() {}
public Vip(int no) {
this.no = no;
}
public Vip(int no, String name) {
this.no = no;
this.name = name;
}
public Vip(int no, String name, String birth) {
this.no = no;
this.name = name;
this.birth = birth;
}
public Vip(int no, String name, String birth, boolean sex) {
this.no = no;
this.name = name;
this.birth = birth;
this.sex = sex;
}
@Override
public String toString() {
return "Vip{" +
"no=" + no +
", name='" + name + '\'' +
", birth='" + birth + '\'' +
", sex=" + sex +
'}';
}
}
public class ReflectTest11 {
public static void main(String[] args) throws Exception{
Class c = Class.forName("bean.Vip");
StringBuilder s = new StringBuilder();
s.append(Modifier.toString(c.getModifiers()));
s.append(" class ");
s.append(c.getSimpleName());
s.append(" {\n");
Constructor[] constructors = c.getDeclaredConstructors();
for (Constructor constructor : constructors) {
s.append("\t");
s.append(c.getSimpleName());
s.append("(");
Class[] parameterTypes = constructor.getParameterTypes();
for (Class parameterType : parameterTypes) {
s.append(parameterType.getSimpleName());
s.append(",");
}
if (parameterTypes.length > 0) {
s.deleteCharAt(s.length() - 1);
}
s.append(")\n");
}
s.append("}");
System.out.println(s.toString());
}
}
public class ReflectTest12 {
public static void main(String[] args) throws Exception {
Class c = Class.forName("bean.Vip");
Constructor constructor = c.getDeclaredConstructor(int.class, String.class, String.class, boolean.class);
Object obj = constructor.newInstance(1, "通信一班", "1997-09-23", true);
System.out.println(obj);
}
}
public class ReflectTest13 {
public static void main(String[] args) throws Exception {
Class c = Class.forName("java.lang.String");
Class superClass = c.getSuperclass();
System.out.println(superClass.getName());
Class[] interfaces = c.getInterfaces();
for (Class in : interfaces) {
System.out.println(in.getName());
}
}
}
[ 修饰符列表 ] @interface 注解类型名{ }
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
/**
* 注解中的属性,看着像是方法,其实是属性
*/
public @interface MyAnnotation {
String name();
String age() default "24";
}
public class AnnotationTest01 {
@MyAnnotation(name = "ylx", age = "12")
public static void m() {
}
}
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
// 属性
String pos() default "上海宝山";
}
@MyAnnotation
public class MyAnnotationTest {
}
public class ReflectAnnotationTest {
public static void main(String[] args) throws Exception {
Class c = Class.forName("annotation.annotation2.MyAnnotationTest");
System.out.println(c.isAnnotationPresent(MyAnnotation.class)); // true
if (c.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation myAnnotation = (MyAnnotation) c.getAnnotation(MyAnnotation.class);
String value = myAnnotation.pos();
System.out.println(value); // 上海宝山
}
}
}
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
// 属性
int age();
String name();
}
public class MyAnnotationTest {
@MyAnnotation(age = 23, name = "zsq")
public void doSome() {
}
}
public class ReflectAnnotationTest {
public static void main(String[] args) throws Exception {
Class c = Class.forName("annotation.annotation2.MyAnnotationTest");
Method method = c.getDeclaredMethod("doSome");
MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
System.out.println(myAnnotation.age());
System.out.println(myAnnotation.name());
}
}
public class NotFoundIdException extends RuntimeException {
public NotFoundIdException() {}
public NotFoundIdException(String s) {
super(s);
}
}
@Id
public class User {
// int id;
String name;
String password;
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Id {
}
public class Test {
public static void main(String[] args) throws Exception {
Class userClass = Class.forName("annotation.annotation3.User");
// 判断该类上是否有Id注解
boolean isOk = false;
if (userClass.isAnnotationPresent(Id.class)) {
Field[] fields = userClass.getDeclaredFields();
for(Field field : fields) {
if ("id".equals(field.getName()) && field.getType().getName() == "int") {
isOk = true;
break;
}
}
if (!isOk) {
throw new NotFoundIdException("没有id属性,不合法!");
}
}
}
}
public class ExceptionTest {
public static void main(String[] args) {
try {
m1();
} catch (ClassNotFoundEception e) {
System.out.println("文件删除或不存在!");
}
}
public static void m1 throws FileNotFoundException() {
new FileInputStr
}
}
public class ExceptionTest01 {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("D://XXX");
}catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if (fis != null) {
try {
fis.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public class ExceptionTest01 {
public static void main(String[] args) {
int result = m();
System.out.println(result);
}
public static void m() {
int i = 100;
try {
return i;
}finally {
i++;
}
}
}
public class MyException extends RuntimeException {
public MyException() {
}
public MyException(String s) {
super(s);
}
}
public class ExceptionTest02 {
public static void main(String[] args) {
MyException me = new MyException("字符串为空");
me.printStackTrace();
String msg = me.getMessage();
System.out.println(msg);
}
}
public class ThreadTest01 {
public static void main(String[] args) {
System.out.println("main begin");
m1();
System.out.println("main end");
}
public static void m1() {
System.out.println("m1 begin");
m2();
System.out.println("m1 end");
}
public static void m2() {
System.out.println("m2 begin");
m3();
System.out.println("m2 end");
}
public static void m3() {
System.out.println("m3 execute");
}
}
public class ThreadTest02 {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
for(int i = 0; i < 1000; ++i) {
System.out.println("main thread--->" + i);
}
}
}
class MyThread extends Thread {
@Override
public void run() {
// 在这里编写程序,这段程序运行在分支线程中
for (int i = 0; i < 1000; ++i) {
System.out.println("other thread--->" + i);
}
}
}
public class ThreadTest03 {
public static void main(String[] args) {
// 创建一个可运行的对象
MyRunnable r = new MyRunnable();
// 将可运行的对象分装成一个线程对象
Thread t = new Thread(r);
// 启动线程
t.start();
for (int i = 0; i < 1000; ++i) {
System.out.println("主线程--->" + i);
}
}
}
// 这并不是一个线程类,是一个可运行的类,还不是一个线程
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 1000; ++i) {
System.out.println("分支线程--->" + i);
}
}
}
thread.getName()
来获取名字thread.setName("名字")
来设置线程名字public class ThreadTest05 {
public static void main(String[] args) {
// 创建线程对象
MyThread2 t = new MyThread2();
// 设置线程的名字
// t.setName("tttt");
// 获取线程的名字
String tName = t.getName(); // 默认为Thread-0
System.out.println(tName);
}
}
class MyThread2 extends Thread {
@Override
public void run() {
for(int i = 0; i < 100; ++i) {
System.out.println("分支线程--->" + i);
}
}
}
Thread t = Thread.currentThread();
返回值t就是当前线程public class ThreadTest05 {
public static void main(String[] args) {
Thread currentThread = Thread.currentThread();
System.out.println(currentThread.getName());
// 创建线程对象
MyThread2 t1 = new MyThread2();
// 设置线程的名字
t1.setName("t1线程");
// 获取线程的名字
String tName = t1.getName(); // 默认为Thread-0
System.out.println(tName);
MyThread2 t2 = new MyThread2();
t2.setName("t2线程");
System.out.println(t2.getName());
t1.start();
t2.start();
}
}
class MyThread2 extends Thread {
@Override
public void run() {
for(int i = 0; i < 100; ++i) {
Thread currentThread = Thread.currentThread();
System.out.println(currentThread.getName() + "--->" + i);
}
}
}
static void sleep(long millis);
public class ThreadTest07 {
public static void main(String[] args) throws InterruptedException {
Thread t = new MyThread3();
t.setName("t");
t.start();
// 出现在main方法中,就让main线程休眠
t.sleep(5000); // 在执行的时候还是会转换成:Thread.sleep(5000);
System.out.println("hello world");
}
}
class MyThread3 extends Thread {
@Override
public void run() {
for (int i = 0; i < 100; ++i) {
System.out.println(Thread.currentThread().getName() + "--->" + i);
}
}
}
public class ThreadTest10 {
public static void main(String[] args) {
MyRunnable4 r = new MyRunnable4();
Thread t = new Thread(r);
t.setName("t1");
t.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
r.run = false;
}
}
class MyRunnable4 implements Runnable {
boolean run = true;
@Override
public void run() {
for (int i = 0; i < 10; ++i) {
if(run) {
System.out.println(Thread.currentThread().getName() + "-->" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
// return之前可以做一些操作如保存等
return;
}
}
}
}
void setPriority(int newPriority);
设置线程优先级void join();
获取线程优先级,最低优先级1,最高10,默认优先级5void join();
合并线程static void yield();
让位方法,使线程从运行状态到就绪状态,让位之后再抢到概率也会低一些线程优先级代码
public class ThreadTest11 {
public static void main(String[] args) {
Thread.currentThread().setPriority(1);
// System.out.println("最高优先级" + Thread.MAX_PRIORITY);
Thread currentThread = Thread.currentThread();
// System.out.println(currentThread.getName() + "线程默认优先级" + currentThread.getPriority());
Thread t = new Thread(new Myrunnable5());
t.setPriority(10);
t.setName("t1");
t.start();
// 优先级较高的只是抢到CPU时间片相对多一些,大概率更偏向于优先级较高的
for (int i = 0; i < 1000; ++i) {
System.out.println(Thread.currentThread().getName() + "--->" + i);
}
}
}
class Myrunnable5 implements Runnable {
@Override
public void run() {
// System.out.println(Thread.currentThread().getName() + "线程默认优先级" + Thread.currentThread().getPriority());
for (int i = 0; i < 1000; ++i) {
System.out.println(Thread.currentThread().getName() + "--->" + i);
}
}
}
线程让位代码
public class ThreadTest12 {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable6());
t.setName("t1");
t.start();
for (int i = 0; i < 10000; ++i) {
System.out.println(Thread.currentThread().getName() + "--->" + i);
}
}
}
class MyRunnable6 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10000; ++i) {
if(i % 100 == 0) {
Thread.yield(); // 当前线程让一下,让给主线程
}
System.out.println(Thread.currentThread().getName() + "--->" + i);
}
}
}
线程合并代码
public class ThreadTest13 {
public static void main(String[] args) {
System.out.println("main begin");
Thread t = new Thread(new MyRunnable7());
t.setName("t1");
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main over");
}
}
class MyRunnable7 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10000; ++i) {
System.out.println(Thread.currentThread().getName() + "--->" + i);
}
}
}
不安全代码
public class Account {
private String actNo;
private double balance;
public Account() {
}
public Account(String actNo, double balance) {
this.actNo = actNo;
this.balance = balance;
}
public String getActNo() {
return actNo;
}
public void setActNo(String actNo) {
this.actNo = actNo;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void withdraw(double money) {
// 取之前的余额
double before = this.getBalance();
// 取之后余额
double after = before - money;
// 假如t1执行到这里之前,t2线程进入withdraw方法调用getBalance()显示余额仍未1w
try {
// 睡眠1s模拟网络延迟
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.setBalance(after);
}
}
public class AccountThread extends Thread{
private Account act;
public AccountThread(Account act) {
this.act = act;
}
public void run() {
// run方法表示取款操作
double money = 5000;
act.withdraw(money);
System.out.println(Thread.currentThread().getName() + "对账户" + act.getActNo() + "取款成功,余额为" + act.getBalance());
}
}
public class Test {
public static void main(String[] args) {
Account act = new Account("act-001", 10000);
Thread t1 = new AccountThread(act);
Thread t2 = new AccountThread(act);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
public class Account {
private String actNo;
private double balance;
public Account() {
}
public Account(String actNo, double balance) {
this.actNo = actNo;
this.balance = balance;
}
public String getActNo() {
return actNo;
}
public void setActNo(String actNo) {
this.actNo = actNo;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void withdraw(double money) {
// 以下这几行代码必须是线程排队的,不能并发
// 一个线程把这里的代码全部执行结束之后,另一个线程才能进来
/*
线程同步机制的语法:
synchronized() {
// 线程同步代码块
}
synchronized后面小括号中传的这个数据是相当关键的,
这个数据必须是多线程共享的数据,才能达到多线程排队
()中写什么?
要看你想让那些线程同步
假设t1,t2,t3,t4,t5有五个线程
你只希望t1,t2,t3排队,t4,t5不需要排队,怎么办?
你一定要在()写一个t1,t2,t3共享的对象,而这个对象对于t4 t5是不共享的
*/
synchronized (this) {
double before = this.getBalance();
double after = before - money;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.setBalance(after);
}
}
}
public class AccountThread extends Thread{
private Account act;
public AccountThread(Account act) {
this.act = act;
}
public void run() {
// run方法表示取款操作
double money = 5000;
act.withdraw(money);
System.out.println(Thread.currentThread().getName() + "对账户" + act.getActNo() + "取款成功,余额为" + act.getBalance());
}
}
public class Test {
public static void main(String[] args) {
Account act = new Account("act-001", 10000);
Thread t1 = new AccountThread(act);
Thread t2 = new AccountThread(act);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
缺点:
优点:
public class Exam01 {
public static void main(String[] args) {
MyClass mc = new MyClass();
Thread t1 = new MyThread(mc);
Thread t2 = new MyThread(mc);
t1.setName("t1");
t2.setName("t2");
t1.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
}
}
class MyThread extends Thread {
private MyClass mc;
public MyThread(MyClass mc) {
this.mc = mc;
}
public void run() {
if (Thread.currentThread().getName().equals("t1")) {
mc.doSome();;
}
if (Thread.currentThread().getName().equals("t2")) {
mc.doOther();
}
}
}
class MyClass {
public synchronized void doSome() {
System.out.println("doSome begin");
try {
Thread.sleep(1000 * 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("doSome over");
}
public void doOther() {
System.out.println("doOther begin");
System.out.println("doOther over");
}
}
public class Exam01 {
public static void main(String[] args) {
MyClass mc1 = new MyClass();
MyClass mc2 = new MyClass();
Thread t1 = new MyThread(mc1);
Thread t2 = new MyThread(mc2);
t1.setName("t1");
t2.setName("t2");
t1.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
}
}
class MyThread extends Thread {
private MyClass mc;
public MyThread(MyClass mc) {
this.mc = mc;
}
public void run() {
if (Thread.currentThread().getName().equals("t1")) {
mc.doSome();;
}
if (Thread.currentThread().getName().equals("t2")) {
mc.doOther();
}
}
}
class MyClass {
public synchronized void doSome() {
System.out.println("doSome begin");
try {
Thread.sleep(1000 * 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("doSome over");
}
public synchronized void doOther() {
System.out.println("doOther begin");
System.out.println("doOther over");
}
}
public class Exam01 {
public static void main(String[] args) {
MyClass mc1 = new MyClass();
MyClass mc2 = new MyClass();
Thread t1 = new MyThread(mc1);
Thread t2 = new MyThread(mc2);
t1.setName("t1");
t2.setName("t2");
t1.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
}
}
class MyThread extends Thread {
private MyClass mc;
public MyThread(MyClass mc) {
this.mc = mc;
}
public void run() {
if (Thread.currentThread().getName().equals("t1")) {
mc.doSome();;
}
if (Thread.currentThread().getName().equals("t2")) {
mc.doOther();
}
}
}
class MyClass {
public synchronized static void doSome() {
System.out.println("doSome begin");
try {
Thread.sleep(1000 * 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("doSome over");
}
public synchronized static void doOther() {
System.out.println("doOther begin");
System.out.println("doOther over");
}
}
public class DeadLock {
public static void main(String[] args) {
Object o1 = new Object();
Object o2 = new Object();
// t1和t2两个线程共享o1和o2
Thread t1 = new MyThread1(o1, o2);
Thread t2 = new MyThread2(o1, o2);
t1.start();
t2.start();
}
}
class MyThread1 extends Thread {
Object o1;
Object o2;
public MyThread1(Object o1, Object o2) {
this.o1 = o1;
this.o2 = o2;
}
public void run() {
synchronized (o1) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o2) {
}
}
}
}
class MyThread2 extends Thread {
Object o1;
Object o2;
public MyThread2(Object o1, Object o2) {
this.o1 = o1;
this.o2 = o2;
}
public void run() {
synchronized (o2) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o1) {
}
}
}
}
t1.setDaemon(true);
*此时t1在所有用户线程结束后会自动结束
public class TimerTest {
public static void main(String[] args) throws Exception {
Timer timer = new Timer();
// Timer timer = new Timer(true); // 设置为守护线程
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date firstTime = sdf.parse("2022-08-07 16:37:00");
timer.schedule(new LogTimerTask(), firstTime, 1000 * 10);
}
}
class LogTimerTask extends TimerTask {
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
String strTime = sdf.format(new Date());
System.out.println(strTime + ": 完成一次数据备份!");
}
}
public class TimerTest {
public static void main(String[] args) throws Exception {
Timer timer = new Timer();
// Timer timer = new Timer(true); // 设置为守护线程
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date firstTime = sdf.parse("2022-08-07 16:37:00");
timer.schedule(new TimerTask(){
@Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
String strTime = sdf.format(new Date());
System.out.println(strTime + ": 完成一次数据备份!");
}
}, firstTime, 1000 * 10);
}
}
public class ThreadTest15 {
public static void main(String[] args) throws Exception {
// 第一步:创建一个“未来任务类”对象
// 第二步:参数非常重要,需要给一个Callable接口实现类对象
FutureTask task = new FutureTask(new Callable() {
@Override
public Object call() throws Exception { // call方法相当于run方法,只是有返回值
System.out.println("call method begin");
Thread.sleep(1000 * 5);
System.out.println("call method end");
int a = 100;
int b = 200;
return a + b; // 自动装箱300编程Integer
}
});
// 创建线程对象
Thread t = new Thread(task);
t.start();
// 这是main方法,主线程中,如何获取t线程的返回结果
Object obj = task.get();
System.out.println(obj.toString());
//main方法剩下代码需要等待get()方法结果,而此方法可能需要很久,另一个线程需要时间
System.out.println("hello world");
}
}
public class ThreadTest16 {
/*
1. 使用wait方法和notify方法实现生产者和消费者模式
2. 什么是生产者和消费者模式?
生产线程负责生产,消费线程负责消费
生产线程he消费线程要达到均衡
这是一种特殊的业务需求,在这种特殊需求的情况下需要使用wait和notify方法
3. 两种方法建立在线程同步的基础上,因为多线程要同时操作一个仓库,有线程安全问题
*/
/*
模拟这样一个需求:
仓库采用list集合。
list集合假设只能存储一个元素
如果list集合中元素个数为0则表示仓库空了
保证list集合中永远最多存1个元素
*/
public static void main(String[] args) {
List list = new ArrayList();
Thread t1 = new Thread(new Producer(list));
Thread t2 = new Thread(new Consumer(list));
t1.setName("生产者线程");
t2.setName("消费者线程");
t1.start();
t2.start();
}
}
// 生产线程
class Producer implements Runnable {
private List list;
public Producer(List list) {
this.list = list;
}
@Override
public void run() {
// 通过死循环模拟一直生产
synchronized (list) {
// 表示给仓库对象加锁
while(true) {
if (list.size() > 9) {
// 当前线程进入等待状态
try {
// 当前线程进入等待状态,并且释放list的锁
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Object obj = new Object();
list.add(obj);
System.out.println(Thread.currentThread().getName() + "生产了" + obj);
// 唤醒消费者进行消费
list.notify();
}
}
}
}
// 消费线程
class Consumer implements Runnable {
private List list;
public Consumer(List list) {
this.list = list;
}
@Override
public void run() {
synchronized (list) {
while (true) {
if (list.size() == 0) {
try {
// 仓库已经空了,消费者线程等待,释放掉list集合的锁
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 程序执行到此处说明仓库中有数据,应该进行消费
Object obj = list.remove(0);
System.out.println(Thread.currentThread().getName() + "消费了" + obj);
list.notify();
}
}
}
}
package io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/*
1. 文件字节输入流,万能的,任何类型的文件都可以采用这个流来读
2. 字节的方式,完成输入的操作,完成度的操作(硬盘 --> 内存)
3.
*/
public class FileInputStreamTest01 {
public static void main(String[] args) {
// 在外部声明,不然在try中声明finally中无法使用
FileInputStream fis = null;
try {
// 创建字节输入流对象
// 以下采用绝对路径方式
// idea会把\变成\\
fis = new FileInputStream("D:/IOExample/temp.txt");
//开始读
// 调用一次read指针移动一个字节
int readData1 = fis.read();
System.out.println(readData1);
int readData2 = fis.read();
System.out.println(readData2);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 在finally语句中确保流关闭
if (fis != null) { // 避免空指针异常
try {
// 关闭流的前提是:流不为空,流是null的时候没必要关闭
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputStreamTest02 {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("D:\\IOExample\\temp.txt");
// while(true) {
// int readData = fis.read();
// if (readData == -1) {
// break;
// }
// System.out.println(readData);
// }
// 改造while循环
int readData = 0;
// 赋值语句和判断语句写在一起
while((readData = fis.read()) != -1) {
System.out.println(readData);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package com.bjpowernode.java.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputStreamTest03 {
/*
int read(byte[] b)
一次最多读取b.length个字节
减少了硬盘和内存的交互,提高程序的执行效率
在byte数组当中读
*/
public static void main(String[] args) {
FileInputStream fis = null;
try {
// idea中默认地址为工程project的根就是idea默认当前路径
fis = new FileInputStream("tempfile.txt");
byte[] bytes = new byte[4];
// 该方法返回的是读到的字节数量
int readCount1 = fis.read(bytes);
System.out.println(readCount1);
System.out.println(new String(bytes)); // abcd
System.out.println(new String(bytes, 0, readCount1)); // abcd
// 此时读到的是ef,并将内存中的ab覆盖
int readCount2 = fis.read(bytes);
System.out.println(readCount2);
System.out.println(new String(bytes)); // efcd
System.out.println(new String(bytes, 0, readCount2)); // ef
// 此时没有字节
int readCount3 = fis.read(bytes);
System.out.println(readCount3);
System.out.println(new String(bytes)); // efcd
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package com.bjpowernode.java.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/*
最终版
*/
public class FileInputStreamTest04 {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("chapter15/src/tempfile3");
byte[] bytes = new byte[4];
int readCount = 0;
while((readCount = fis.read(bytes)) != -1) {
System.out.print(new String(bytes, 0, readCount));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package com.bjpowernode.java.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/*
其他常用方法:
int available();返回流当中剩余的没有读到的字节数量
long skip(long n);跳过几个字节不读
*/
public class FileInputStreamTest05 {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("tempfile.txt");
System.out.println("总字节数:" + fis.available());
// int readByte = fis.read();
// System.out.println("剩下未读字节数:" + fis.available());
// 该方法不适合大文件
byte[] bytes = new byte[fis.available()];
int readCount = fis.read(bytes);
System.out.println(new String(bytes));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package com.bjpowernode.java.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputStreamTest06 {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("tempfile.txt");
fis.skip(3);
System.out.println(fis.read());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package com.bjpowernode.java.io;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/*
文件字节输出流,负责写
从内存到硬盘
*/
public class FileOutputStreamTest01 {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
// 这种方式会将源文件清空,然后重新写入
// fos = new FileOutputStream("myfile");
// FileOutputStream(String name, boolean append);使用这种构造方法可以选择是清空写还是追加写
fos = new FileOutputStream("myfile", true);
// 开始写
byte[] bytes = {97, 98, 99, 100};
// 将byte数组全部写出,没有文件将自动创建
fos.write(bytes);
fos.write(bytes, 0, 2); // abcdab
String s = "我是一个中国人";
// 将字符串转为byte数组
byte[] bs = s.getBytes();
fos.write(bs);
// 写完之后要刷新
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package com.bjpowernode.java.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/*
使用FileInputStream和FileOutputStream完成文件的拷贝
拷贝的过程是一边读一边写
使用以上字节流拷贝文件的时候,文件类型随意,万能
*/
public class Copy01 {
public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("E:\\mathModel\\2021年中国研究生数学建模竞赛赛题\\1.csv");
fos = new FileOutputStream("E:\\1.csv");
byte[] bytes = new byte[1024 * 1024]; // 一次1MB
int readCount = 0;
while ((readCount = fis.read(bytes)) != -1) {
fos.write(bytes, 0, readCount);
}
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package com.bjpowernode.java.io;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/*
文件字符输入流,只能服务普通文本
读取文本内容时,比较方便,快捷
*/
public class FileReaderTest {
public static void main(String[] args) {
FileReader reader = null;
try {
reader = new FileReader("tempfile.txt");
// 开始读
char[] chars = new char[4];
int readCount = 0;
while ((readCount = reader.read(chars)) != -1) {
System.out.print (new String(chars, 0, readCount));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package com.bjpowernode.java.io;
import java.io.FileWriter;
import java.io.IOException;
/*
文件字符输出流,写
只能输出普通文本
*/
public class FileWriterTest {
public static void main(String[] args) {
FileWriter out = null;
try {
out = new FileWriter("file", true);
// 开始写
char[] chars = {'我', '是','中', '国', '人'};
// 可以是字符数组
out.write(chars);
// 可以是字符数组一部分
out.write(chars, 2, 3);
// 可以是一个字符串
out.write("我是一名java软件工程师");
// 刷新
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.bjpowernode.java.io;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Copy02 {
public static void main(String[] args) {
FileReader reader = null;
FileWriter writer = null;
try {
reader = new FileReader("E:\\mathModel\\2021年中国研究生数学建模竞赛赛题\\123.txt");
writer = new FileWriter("E:\\123_copy.txt");
char[] chars = new char[1024 * 1024];
int readCount = 0;
while((readCount = reader.read(chars)) != -1) {
writer.write(chars, 0, readCount);
}
// 刷新
writer.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package com.bjpowernode.java.io;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/*
BufferedReader:
带有缓冲区的字符输入流,使用这个流的时候不需要自定义char数组,或者说不需要自定义byte数组,自带缓冲
*/
public class BufferedReaderTest01 {
public static void main(String[] args) {
// 当一个流的构造方法中需要一个流的时候,这个被传进来的流叫做:节点流
// 外部负责包装的这个流,叫做包装流,还有一个名字叫做:处理流
// 向当前这个程序来说,fileReader就是一个节点流,BufferedReader就是包装流/处理流
FileReader reader = null;
BufferedReader br = null;
try {
reader = new FileReader("Copy02_copy.java");
br = new BufferedReader(reader);
// 读一行
// String firstLine = br.readLine();
// System.out.println(firstLine);
//
// String secondLine = br.readLine();
// System.out.println(secondLine);
//
// String thirdLine = br.readLine();
// System.out.println(thirdLine);
String s = null;
// readLine()方法读取一个文本行但是不带换行符
while ((s = br.readLine()) != null) {
System.out.println(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
// 关闭流
// 对于包装流来说,只需要关闭最外层流就行,里面的节点流会自动关闭
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package com.bjpowernode.java.io;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
public class BufferedReaderTest02 {
public static void main(String[] args) throws Exception {
// // 字节流
// FileInputStream in = new FileInputStream("Copy02_copy.java");
// // 将字节流转换为字符流
// InputStreamReader reader = new InputStreamReader(in);
// // 这个构造方法只能传一个字符流,不能传字节流,需要转换
// BufferedReader br = new BufferedReader(reader);
//合并
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("Copy02_copy.java")));
String s = null;
while ((s = br.readLine()) != null) {
System.out.println(s);
}
br.close();
}
}
package com.bjpowernode.java.io;
import java.io.*;
public class BufferedWriterTest {
public static void main(String[] args) throws Exception {
// BufferedWriter bw = new BufferedWriter(new FileWriter("copy"));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("copy", true)));
bw.write("Hello world!");
bw.write('\n');
bw.write("Hello ylx!");
bw.flush();
bw.close();
}
}
package com.bjpowernode.java.io;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
/*
java.io.DataOutputStream:数据专属的流
这个流可以将数据连同数据的类型一并写入文档
注意:这个文件不是普通的文本文档。(这个文件使用记事本打不开)
*/
public class DataOutputStreamTest {
public static void main(String[] args) throws Exception {
// 创建数据专属的字节输出流
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data"));
// 写数据
byte b = 100;
short s = 200;
int i = 1000000000;
long l = 400L;
float f = 3.0F;
double d = 3.14;
boolean sex = true;
char c = 'a';
// 写
dos.writeByte(b);
dos.writeShort(s);
dos.writeInt(i);
dos.writeLong(l);
dos.writeFloat(f);
dos.writeDouble(d);
dos.writeBoolean(sex);
dos.writeChar(c);
dos.flush();
dos.close();
}
}
package com.bjpowernode.java.io;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
/*
DataInputStream:数据字节输入流
DataOutputStream写的文件,只能使用DataInputStream去读,并且读的时候你需要提前知道写入的顺序
读的顺序需要和写的顺序一致,才可以正常取出数据
*/
public class DataInputStreamTest01 {
public static void main(String[] args) throws Exception {
DataInputStream dis = new DataInputStream(new FileInputStream("data"));
// 开始读
byte b = dis.readByte();
short s = dis.readShort();
int i = dis.readInt();
System.out.println(b);
System.out.println(s);
System.out.println(i);
}
}
package com.bjpowernode.java.io;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
/*
java.io.PrintStream:标准的字节输出流
*/
public class PrintStreamTest {
public static void main(String[] args) throws Exception {
// 合并写
System.out.println("Hello World!");
// 分开写
PrintStream ps = System.out; // out为静态的标准字节输出流对象
ps.println("Hello World!");
// 标准输出流不再指向控制台,指向log文件
PrintStream printStream = new PrintStream(new FileOutputStream("log", true));
// 修改输出方向,将输出方向修改到log文件
System.setOut(printStream);
// 再输出
System.out.println("hello world");
System.out.println("hello ylx");
// 标准输出流不需要手动关闭
}
}
package com.bjpowernode.java.io;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
日志工具
*/
public class Logger {
public static void log(String msg) {
try {
// 指向一个日志文件
PrintStream ps = new PrintStream(new FileOutputStream("log.txt", true));
// 改变输出方向
System.setOut(ps);
// 日期当前时间
Date nowTime = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
String strTime = sdf.format(nowTime);
System.out.println(strTime + ": " + msg);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
package com.bjpowernode.java.io;
/*
测试工具类是否好用
*/
public class LogTest {
public static void main(String[] args) {
Logger.log("调用了System类的gc()方法,建议启动垃圾回收");
Logger.log("调用了UserService的doSome()方法");
Logger.log("用户尝试登录,验证失败");
}
}
package com.bjpowernode.java.io;
import java.io.File;
import java.io.IOException;
/*
File
1. File类和四大家族没有关系,所以File类不能完成文件的读和写
2. File对象代表什么呢?
文件和目录路径名的抽象表示形式
一个File对象有可能对应的是目录,也可能是文件
File只是一个路径名的抽象表示形式
3. File类中常用的方法
*/
public class FileTest01 {
public static void main(String[] args) throws Exception {
// 创建File对象
File f1 = new File("D:\\file");
// 判断是否存在
System.out.println(f1.exists());
// // 如果D:/file不存在,则以文件的形式创建出来
// if (!f1.exists()) {
// f1.createNewFile();
// }
// // 如果D:/file不存在,则以目录的形式创建
// if (!f1.exists()) {
// f1.mkdir();
// }
// // 创建多重目录
// File f2 = new File("D:/a/b/c/d");
// System.out.println(f2.exists());
// if (!f2.exists()) {
// f2.mkdirs();
// }
// 获取父路径
File f3 = new File("D:\\a\\b\\c\\d\\123.docx");
String parentPath = f3.getParent();
System.out.println(parentPath);
// 第二种方法获取父路径
File parentFile = f3.getParentFile();
System.out.println("获取绝对路径:" + parentFile.getAbsolutePath());
File f4 = new File("copy");
System.out.println("绝对路径为:" + f4.getAbsolutePath());
}
}
boolean exists()
boolean createNewFile();
boolean mkdir();
boolean mkdirs();
File f1 = new File(String pathname); // 构造方法
File getParentFile();
String getAbsolutePath();
package com.bjpowernode.java.io;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
File类的常用方法
*/
public class FileTest02 {
public static void main(String[] args) {
File f1 = new File("copy");
// 获取文件名
System.out.println(f1.getName());
// 判断是否是一个目录
System.out.println(f1.isDirectory());
// 判断是否是一个文件
System.out.println(f1.isFile());
// 获取文件最后一个修改时间
long haoMiao = f1.lastModified();
Date time = new Date(haoMiao);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
String strTime = sdf.format(time);
System.out.println(strTime);
// 获取文件大小
System.out.println(f1.length());
}
}
package com.bjpowernode.java.io;
import java.io.File;
/*
File中的listFiles()方法
*/
public class FileTest03 {
public static void main(String[] args) {
// File[] listFiles()
// 获取当前目录下所有的文件
File f = new File("E:\\ShanghaiUniversity\\QT功能实现汇总");
File[] files = f.listFiles();
for (File file : files) {
System.out.println(file.getAbsolutePath());
}
}
}
package com.bjpowernode.java.io;
import java.io.*;
public class CopyAll {
public static void main(String[] args) {
File srcFile = new File("E:\\ShanghaiUniversity\\personal\\专利");
File destFile = new File("D:\\a\\b\\c\\d\\");
copyDir(srcFile, destFile);
}
private static void copyDir(File srcFile, File destFile) {
if (srcFile.isFile()) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
String path = (destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath()) + "\\" + srcFile.getAbsolutePath().substring(3);
// System.out.println(path);
// 读文件
fis = new FileInputStream(srcFile);
// 写到这个文件中
fos = new FileOutputStream(path);
// 一边读一边写
byte[] bytes = new byte[1024 * 1024];
int readCount = 0;
while ((readCount = fis.read(bytes)) != -1) {
fos.write(bytes,0, readCount);
}
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return;
}
// 获取源下面的子目录
File[] files = srcFile.listFiles();
for (File file : files) {
// 获取所有文件(包括目录和文件)的绝对路径
// System.out.println(file.getAbsolutePath());
if (file.isDirectory()) {
// 新建对应目录
String srcDir = file.getAbsolutePath();
// System.out.println(srcDir.substring(3));
String destDir = destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\\" + srcDir.substring(3);
System.out.println(destDir);
File newFile = new File(destDir);
if (!newFile.exists()) {
newFile.mkdirs();
}
}
copyDir(file, destFile);
}
}
}
package com.bjpowernode.java.bean;
import java.io.Serializable;
public class Student implements Serializable {
private int no;
private String name;
public Student() {
}
public Student(int no, String name) {
this.no = no;
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"no=" + no +
", name='" + name + '\'' +
'}';
}
}
package com.bjpowernode.java.io;
import com.bjpowernode.java.bean.Student;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
/*
1. 参与序列化和反序列化的对象,必须实现Serializable接口
2. 通过源代码发现,Serializable接口只是一个标志接口,接口中没有代码,起到标识的作用,java虚拟机看到这个类实现了这个接口,可能会对这个类进行特殊待遇
3. java虚拟机看到实现该接口的类会自动生成序列化版本号
*/
public class ObjectOutputStreamTest01 {
public static void main(String[] args) throws Exception {
Student s = new Student(1111, "zhangsan");
// 序列化
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("students"));
//序列化对象
oos.writeObject(s);
//刷新
oos.flush();
// 关闭
oos.close();
}
}
package com.bjpowernode.java.io;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ObjectInputStreamTest01 {
public static void main(String[] args) throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("students"));
// 开始反序列化,读
Object obj = ois.readObject();
System.out.println(obj);
ois.close();
}
}
package com.bjpowernode.java.bean;
import java.io.Serializable;
public class User implements Serializable {
private int no;
private String name;
public User() {
}
public User(int no, String name) {
this.no = no;
this.name = name;
}
@Override
public String toString() {
return "User{" +
"no=" + no +
", name='" + name + '\'' +
'}';
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.bjpowernode.java.io;
import com.bjpowernode.java.bean.User;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class ObjectOutputStreamTest02 {
public static void main(String[] args) throws Exception {
List<User> list = new ArrayList<User>();
list.add(new User(1, "zhangsan"));
list.add(new User(2, "lisi"));
list.add(new User(3, "wangwu"));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("users"));
// 序列化一个集合,这个集合中有多个对象
oos.writeObject(list);;
oos.flush();
oos.close();
}
}
package com.bjpowernode.java.io;
import com.bjpowernode.java.bean.User;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.List;
public class ObjectInputStreamTest02 {
public static void main(String[] args) throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("users"));
List<User> list = (List<User>)ois.readObject();
for (User user : list) {
System.out.println(user);
}
ois.close();
}
}