java50-100
日期类Date
Java.util.date
package 1_package_date;
import java.util.Date;
public class Test {
public static void main(String[] args) {
Date d = new Date();
System.out.println(d);//Fri Jul 01 18:47:30 CST 2022
System.out.println(d.toGMTString());
System.out.println(d.toString());
System.out.println( d.getTime());//1656671773612
System.out.println( System.currentTimeMillis());//static静态的,可以直接类名.方法名调用
/*
public static native long currentTimeMillis();//native是本地方法,不是通过Java写的
*/
System.out.println( d.getMonth()+1);
System.out.println( d.getYear()+1900);
}
}
Util 和sql的区别
Util:年月日时分秒 sql:年月日 sql继承util Java.sql.date
package 1_package_date;
import java.sql.Date;
public class Test2 {
public static void main(String[] args) {
Date d = new Date(1656671947888L);
System.out.println(d);//2022-07-01
//java.util.Date->java.sql.Date
java.util.Date date = new Date(1656671947888L);//创建util对象
//向下转型
Date date1 = (Date) date;
//利用构造器转
Date date2 = new Date(date.getTime());
//sql->util
java.util.Date date3 = d;
//String->sql date
Date date4 = Date.valueOf("2022-07-01");
}
}
将String转为java.util.Date String->java.sql.Date->java.util.Date
package 1_package_date;
public class Test3 {
public static void main(String[] args) {
//第一步String->java.sql.Date
java.sql.Date date = java.sql.Date.valueOf("2022-07-01");//只能是年-月-日格式
//第二步java.sql.Date->java.util.Date
java.util.Date date2 = date;
System.out.println(date2.toString());
}
}
SimpleDateFormat类
package 1_package_date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test4 {
public static void main(String[] args) {
//日期转换:
//SimpleDateFormat()继承于DateFormat(),DateFormat()是一个抽象类
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义格式化标准
//String->date
try {
Date d = df.parse("2022-7-1 22:23:23");
System.out.println(d);
} catch (ParseException e) {
e.printStackTrace();
}
//date->String
String format = df.format(new Date());
System.out.println(format);
}
}
Calendar类
用的比较少
package 1_package_date;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Test5 {
public static void main(String[] args) {
//Calendar()是一个抽象类,不能被实例化,GregorianCalendar()继承Calendar()
Calendar cal = new GregorianCalendar();
Calendar cal2 = Calendar.getInstance();
System.out.println(cal);
//常用方法
//get方法
System.out.println(cal.get(Calendar.YEAR));
System.out.println(cal.get(Calendar.MONTH));
System.out.println(cal.get(Calendar.DATE));
System.out.println(cal.getActualMaximum(Calendar.DATE));
//set方法,可以改变Calendar中的内容
cal.set(Calendar.YEAR,1990);
cal.set(Calendar.MONTH,4);
cal.set(Calendar.DATE,23);
System.out.println(cal);
//String->Calendar分解步骤
//1)String->java.sql.Date
java.sql.Date date = java.sql.Date.valueOf("2020-09-09");
//2)java.sql.Date->Calendar
cal.setTime(date);
System.out.println(cal);
}
}
localDateTime
package 1_package_date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Test7 {
public static void main(String[] args) {
//now方法
LocalDate localDate = LocalDate.now();
System.out.println(localDate);
LocalTime localTime = LocalTime.now();
System.out.println(localTime);
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime);//2022-07-04T09:25:48.870
//of()
LocalDate of1 = LocalDate.of(2022 , 7, 4);
LocalTime of2 = LocalTime.of(9,24);
LocalDateTime of3 = LocalDateTime.of(2022 , 7, 4,9,24);
System.out.println(of3);
//LocalDateTime用的比较多
//一些列常用的get**
localDateTime.getMonth();
localDateTime.getDayOfWeek();
localDateTime.getHour();
System.out.println(localDateTime.getYear());
//with,不可变性,新的时间被改了,原来的日期没改
LocalDateTime localDateTime1 = localDateTime.withMonth(8);
System.out.println(localDateTime);//2022-07-04T09:36:36.657
System.out.println(localDateTime1);//2022-08-04T09:36:36.657
//提供了加操作
LocalDateTime localDateTime2 = localDateTime.plusMonths(4);
System.out.println(localDateTime2);//2022-11-04T09:36:36.657
//减
LocalDateTime localDateTime3 = localDateTime.minusMonths(3);
System.out.println(localDateTime3);//2022-04-04T09:38:38.044
}
}
DateTimeFormatter
package 1_package_date;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
public class Test8 {
public static void main(String[] args) {
//预定义标准格式, ISO_LOCAL_DATE_TIME
DateTimeFormatter df1 = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
//LocalDateTime->String
LocalDateTime now = LocalDateTime.now();
String str = df1.format(now);
System.out.println(str);//2022-07-04T09:44:50.647
System.out.println(df1.parse(str));//{},ISO resolved to 2022-07-04T09:44:50.647
//本地化格式,oflocalizedDateTime
DateTimeFormatter df2 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
LocalDateTime now1 = LocalDateTime.now();
String str2 = df2.format(now1);
System.out.println(str2);//2022年7月4日 上午09时48分33秒
System.out.println(df2.parse(str2));
//自定义格式, ofPattern("yyyy-MM-dd hh:mm:ss"),常用的
DateTimeFormatter df3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
//LocalDateTime->String
LocalDateTime now3 = LocalDateTime.now();
String str3 = df3.format(now3);
System.out.println(str3);//2022-07-04 09:52:31
//String->LocalDateTime
System.out.println(df3.parse(str3));//{HourOfAmPm=9, NanoOfSecond=0, MicroOfSecond=0, MilliOfSecond=0, SecondOfMinute=24, MinuteOfHour=53},ISO resolved to 2022-07-04
}
}
Math类
无需导包,final修饰类不能被继承 所有的方法都被static修饰
package 1_package_math;
public class Test1 {
public static void main(String[] args){
//常用属性
System.out.println(Math.PI);//3.141592653589793
//常用方法
System.out.println("随机数:" + Math.random());//[0.0, 1.0)
System.out.println("绝对值:" + Math.abs(-80));//绝对值:80
System.out.println("向上取值:" + Math.ceil(9.1));//向下取值:10.0
System.out.println("向下取值:" + Math.floor(9.1));//向下取值:9.0
System.out.println("四舍五入:" + Math.round(9.5));//四舍五入:10
System.out.println("取最大值:" + Math.max(4.4, 5.5));//取最大值:5.5
System.out.println("取最小值:" + Math.min(4.4, 5.5));//取最小值:4.4
}
}
package 1_package_math;
import static java.lang.Math.*;//这种方法导入静态包后,后面调用math方法时可以不写类名
public class Test1 {
public static void main(String[] args){
//常用属性
System.out.println(Math.PI);//3.141592653589793
//常用方法
System.out.println("随机数:" +random());//这里优先用的是本类中的方法
System.out.println("绝对值:" + Math.abs(-80));//绝对值:80
}
public static int random(){
return 100;
}
}
random类
package 1_package_random;
import java.util.Random;
public class Test {
public static void main(String[] args){
//利用带参数构造器创建对象
Random r1 = new Random(System.currentTimeMillis());
System.out.println(r1.nextInt());
//利用空参构造器创建对象
Random r2 = new Random();
System.out.println(r2.nextInt(10));//0到指定值之间
System.out.println(r2.nextDouble());//0.0到1.0之间
}
}
String类
无需导包,final修饰 字符串底层是一个char类型的数组
package 1_package_tostring;
import java.util.Arrays;
public class Test1 {
public static void main(String[] args){
//声明字符串变量
String str = "asd";
System.out.println(str);
//通过构造器创建字符串
String str1 = new String();
String str2 = new String("12");
String str3 = new String(new char[]{'a', 'b'});
//常用方法
String str4 = "abc";
System.out.println("长度:" + str4.length());
System.out.println("是否为空:" + str4.isEmpty());
System.out.println("获取字符串下标对应的字符:" + str4.charAt(1));//b
//equals方法
String str6 = "abcq";
String str7 = "abcqwe";
System.out.println(str6.equals(str7));
//compareto方法
System.out.println(str6.compareTo(str7));//-2,返回不一样那一位的ASCII码的差值一样的话就返回0
//subString字符串截取
System.out.println(str7.substring(3));
System.out.println(str7.substring(3,6));
//concat字符串拼接
System.out.println(str6.concat(str7));//abcqabcqwe
//replace替换
System.out.println(str6.replace("abc", "***"));//***q
//split分割
String str8 = "a-b-c-d";
String[] str9 = str8.split(" ");
System.out.println(Arrays.toString(str9));//[a-b-c-d]
//toUpperCase,toLowerCase转大小写
System.out.println(str6.toUpperCase());//ABCQ
System.out.println(str6.toLowerCase());//abcq
//trim去除首尾空格
String str10 = " abc ";
System.out.println(str10.trim());//abc
//toString
System.out.println(str10.toString());
//valueOf转为String类型
System.out.println(String.valueOf(false));
}
}
StringBudier类
字符串分为可变和不可变类型,不可变:String, 可变:stringBuilder,StringBuffer
package 1_package_stringbuilder;
public class Test {
public static void main(String[] args){
//利用构造器创建对象
StringBuilder stringBuilder = new StringBuilder();
StringBuilder stringBuilder1 = new StringBuilder(23);
StringBuilder stringBuilder2 = new StringBuilder("abc");
stringBuilder2.append("def");
System.out.println(stringBuilder2);//abcdef
//不可变,指的是字符串的地址没有改变
System.out.println(stringBuilder2.append("def") == stringBuilder2.append("qqq"));//true
//StringBuilder常用方法
stringBuilder2.insert(1,"ooo");
stringBuilder2.replace(1, 5, "eeeee");
stringBuilder2.delete(1, 3);
stringBuilder2.reverse();
stringBuilder2.substring(2,4);
stringBuilder2.charAt(1);
System.out.println(stringBuilder2);
}
}
}
String、StringBuffer、StringBuilder
String是final修饰的,不可变,每次操作都会产生新的String对象 StringBuffer和StringBuilder都是在原对象上操作 StringBuffer是线程安全的,StringBuilder线程不安全的 StringBuffer方法都是synchronized修饰的 性能:StringBuilder > StringBuffer > String 场景:经常需要改变字符串内容时使用后面两个 优先使用StringBuilder,多线程使用共享变量时使用StringBuffer
Junit
main方法中测试会有局限 将测试和业务分离 导入junit.jar,hamcrest-2.2.jar
@Before中一般加入申请资源的代码 @After中加入释放资源的代码
package Calculator;
public class Calculator {
//加法
public int add(int a, int b){
return a + b;
}
//减法
public int sub(int a, int b){
return a - b;
}
}
package CalculatorTest;
import Calculator.Calculator;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class CalculatorTest {
@Before
public void init(){
System.out.println("方法测试开始了");
}
@After
public void close(){
System.out.println("方法测试结束了");
}
//测试add
@Test
public void testAdd(){
System.out.println("测试加法");
Calculator cal = new Calculator();
int result = cal.add(10, 30);
//System.out.println(result);、、程序的运行结果不关注
//加入断言,判断预期结果是否达到
Assert.assertEquals(40, result);
}
//测试sub
@Test
public void testSub(){
System.out.println("测试减法");
}
}
注解
框架=注释+反射+设计模式
文档注解
Javadoc,文档注解一般放在文档注释中,配合javadoc工具 生成注解文档:tools-generate javadoc
package anno;
/**
* @author:1
* @version:v1.0
* */
public class Person {
/**
* @param num1 就餐人数
* @param num2 点餐人数
* */
public void eat(int num1, int num2){
}
/**
* @param age
* @return int
* @exception RuntimeException 当年龄过大时侯
* @exception IndexOutOfBoundsException 当年龄过小时候
* @see Student
*/
public int sleep(int age){
new Student();
if(age >100){
throw new RuntimeException();
}
if(age <0){
throw new IndexOutOfBoundsException();
}
return 10;
}
}
package anno;
public class Student {
}
@override
限定重写方法,防止方法写错
package anno.anno2;
public class Person {
public void eat(){
}
}
package anno.anno2;
public class Student extends Person {
@Override
public void eat(){
System.out.println("重写eat方法");
}
}
@Deprecated
废弃方法
@SuppressWarnings
@SuppressWarnings ({"unused","rwatypes"})抑制警告
自定义注解
一般用得不多,java自带注解基本够用,不需要自己写注解
package anno3;
//定义注解
public @interface MyAnnotation {
String[] value();
}
//使用注解
package anno3;
@MyAnnotation("abc")
public class Person {
}
元注解
元注解用于修饰其他注解 @Retention用于声明指定注解的生命周期,包含一个RetentionPolicy枚举类型的成员变量 如果没有声明时,默认用的就是.CLASS类型 @Retention(RetentionPolicy.SOURCE),在源文件中有效 @Retention(RetentionPolicy.CLASS),在class文件中有效,存在字节码中 @Retention(RetentionPolicy.RUNTIME),在运行时有效 @Target用于指定被修饰的注解能用于修饰哪些程序元素,包含一个名为value的成员变量
枚举
一个一个列出来,前提:有限的,确定的 在Java中,类的对象是有限个,确定的,这个类就可以定义为枚举类 比如:星期,性别,季节
枚举类定义
package Enum;
/***
* 定义枚举类
*/
public class Season {
//属性
private final String seasonName;
private String seasonDesc;
//利用构造器对属性进行赋值操作
//构造器私有化,外界不能调用这个构造器,只能内部调用
private Season(String seasonName, String seasonDesc){
this.seasonName = seasonName;
this.seasonDesc =seasonDesc;
}
//提供的枚举类型是有限的
public static Season spring = new Season("春天","春暖花开");
public static Season summer = new Season("夏天","烈日炎炎");
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
@Override
public String toString() {
return "Season{" +
"seasonName='" + seasonName + '\'' +
", seasonDesc='" + seasonDesc + '\'' +
'}';
}
}
package Enum;
public class TestSeason {
public static void main(String[] args){
Season summer = Season.summer;
System.out.println(summer.toString());//Season{seasonName='夏天', seasonDesc='烈日炎炎'}
System.out.println(summer.getSeasonName());//夏天
}
}
使用Enum关键字创建枚举类
Jdk1.5之后,使用Enum关键字创建枚举类
package Enum2;
//利用enum定义枚举类
public enum Season {
//提供的枚举类型是有限的
//多个元素之间用逗号连接,最后一个用分号
spring ("春天","春暖花开"),
summer ("夏天","烈日炎炎");
//属性
private final String seasonName;
private String seasonDesc;
//利用构造器对属性进行赋值操作
//构造器私有化,外界不能调用这个构造器,只能内部调用
private Season(String seasonName, String seasonDesc){
this.seasonName = seasonName;
this.seasonDesc =seasonDesc;
}
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
/*
@Override
public String toString() {
return "Season{" +
"seasonName='" + seasonName + '\'' +
", seasonDesc='" + seasonDesc + '\'' +
'}';
}
*/
}
package Enum2;
public class Test {
public static void main(String[] args){
Season spring = Season.spring;
System.out.println(spring);
//使用enum创建的枚举类的父类是enum
System.out.println(Season.class.getSuperclass().getName());//java.lang.Enum
}
}
源码中看起来比较简单的枚举类
package Enum2;
public enum Season {
spring,
summer,
autumn,
winter;
}
常用方法
package enum3;
public class Test {
public static void main(String[] args){
//toString
Season autumn = Season.autumn;
System.out.println(autumn.toString());
//values
Season[] values = Season.values();
for(Season s:values){
System.out.println(s);
}
System.out.println("--------");
//valueOf,值必须传对
Season autumn1 = Season.valueOf("autumn");
System.out.println(autumn1);
}
}
枚举类实现接口
package Enum4;
public interface TestInterface {
void show();
}
package Enum4;
public enum Season implements TestInterface{
spring,
summer{
@Override
public void show() {
System.out.println("这是夏天");
}
},
autumn,
winter;
@Override
public void show() {
System.out.println("这是season类");
}
}
package Enum4;
public class Test {
public static void main(String[] args) {
Season autumn = Season.autumn;
autumn.show();//这是season类
Season summer = Season.summer;
summer.show();//这是夏天
}
}
枚举的应用
例1
package Enum5;
public enum Gender {
男,
女;
}
package Enum5;
public class Test2 {
public static void main(String[] args){
Gender sex = Gender.男;
//switch后面可以放int, byte, short, char, String,枚举
switch (sex){
case 女:
System.out.println("是个女孩");
case 男:
System.out.println("是个男孩");
}
}
}
例2
package Enum5;
public class Person {
private int age;
private String name;
private Gender sex;
public int getAge() {
return age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Gender getSex() {
return sex;
}
public void setSex(Gender sex) {
this.sex = sex;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
", sex=" + sex +
'}';
}
}
package Enum5;
public class Test {
public static void main(String[] args){
Person p = new Person();
p.setAge(23);
p.setName("lili");
p.setSex(Gender.男);
System.out.println(p);
}
}
File类
文件
package file;
import java.io.File;
import java.io.IOException;
public class Test1 {
public static void main(String[] args) throws IOException {
//将文件封装为一个对象
File f = new File("C:\\Users\\1\\IdeaProjects\\1_project\\test.txt");
File f2 = new File("C:\\Users\\1\\IdeaProjects\\1_project\\test.txt");
//File.separator属性能够获取当前系统的路径拼接符号
File f1 = new File("d:"+File.separator+"test.txt");
//常用方法
System.out.println( "文件是否可读:"+ f.canRead());
System.out.println( "文件是否可写:"+ f.canWrite());
System.out.println( "文件是的名字:"+ f.getName());
System.out.println( "文件的上级目录:"+ f.getParent());
System.out.println( "文件是否是一个目录:"+ f.isDirectory());
System.out.println( "文件是否是一个文件:"+ f.isFile());
System.out.println( "文件是否隐藏:"+ f.isHidden());
System.out.println( "文件的大小:"+ f.length());
System.out.println( "文件是否隐藏:"+ f.exists());
/*
判断文件是否存在,存在则删除,不存在则创建
if(f.exists()){
f.delete();
}else {
f.createNewFile();
}
*/
System.out.println(f1 == f2);//比较2个对象的地址
System.out.println(f1.equals(f2));//比较对应的文件路径
//跟路径相关的
File f4 = new File("demo.txt");
if(!f4.exists()){
f4.createNewFile();
}
//绝对路径指的就是完整的精准的路径
System.out.println("绝对路径:" + f4.getAbsoluteFile());//绝对路径:C:\Users\1\IdeaProjects\1_project\demo.txt
//相对路径有一个参照物
System.out.println("相对路径:" + f4.getPath());//相对路径:demo.txt
//toString的效果就是相对路径的效果
System.out.println("toString:" + f4.toString());//toString:demo.txt
}
}
目录
package file;
import java.io.File;
import java.io.IOException;
public class Test2 {
public static void main(String[] args) throws IOException {
//将目录封装为对象
File f = new File("C:\\Users\\1\\IdeaProjects\\1_project");
//常用方法
System.out.println( "文件是否可读:"+ f.canRead());
System.out.println( "文件是否可写:"+ f.canWrite());
System.out.println( "文件是的名字:"+ f.getName());
System.out.println( "文件的上级目录:"+ f.getParent());
System.out.println( "文件是否是一个目录:"+ f.isDirectory());
System.out.println( "文件是否是一个文件:"+ f.isFile());
System.out.println( "文件是否隐藏:"+ f.isHidden());
System.out.println( "文件的大小:"+ f.length());
System.out.println( "文件是否隐藏:"+ f.exists());
System.out.println("绝对路径:" + f.getAbsoluteFile());
System.out.println("相对路径:" + f.getPath());
//跟目录相关的方法
File f2 = new File("C:\\a\\b\\c");
//创建目录
//f2.mkdir();//创建单层目录
//f2.mkdirs();//创建多层目录
//f2.delete();//删除最里面的一个目录,前提是该目录下是空的
//查看
String[] list = f.list();//文件夹下目录或者文件对应的名字的数组
for(String s:list){
System.out.print("\t"+s);
}
File[] files = f.listFiles();//作用更广,可以返回绝对路径等
for(File file: files){
System.out.println(file.getAbsoluteFile());
}
}
}
IO流
理解为一根管子,程序和数据源沟通的桥梁 按照方向分类:输入流InputStream(Reader),输出流OputStream(Writer) 按处理单位分类:字节流,字符流 按照功能:节点流(单独处理一根管对应的那个流),处理流(管套着管,组合使用) 不要用字符流去操作非文本文件 文本文件:txt, java, c->使用字符流操作(字节流会把文本文件中的一个中文字拆成3个) 非文本文件:jpg, mp3, doc, ppt->使用字节流操作 字符流: Reader Writer FileReader FileWriter BufferReader BufferWriter InputStreamReader OutputStreamWriter
字节流: InputStream OutputStream FileInputStream FileOutputStream BufferedInputStream BufferedOutputStream ObjectInputStream ObjectOutputStream
FileReader
文件-》程序 一个字节一个字节读取
package io;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Test1 {
public static void main(String[] args) throws IOException {
//文件-》程序
//1.创建文件对象
File f = new File("C:\\Users\\1\\IdeaProjects\\1_project\\test.txt");
//2.利用fileReader找到文件
FileReader fr = new FileReader(f);
//3.读取
/*文件内容是"abc老师"
int n1 = fr.read();
int n2 = fr.read();
int n3 = fr.read();
int n4 = fr.read();
int n5 = fr.read();
System.out.println(n1);
System.out.println(n2);
System.out.println(n3);
System.out.println(n4);
System.out.println(n5);
System.out.println(n6);//-1
*/
//方式1
/*
int n = fr.read();
while (n != -1){//到了文件结尾处读的是-1
System.out.println(n);//9798993276924072输出的是字节流
n = fr.read();
}
*/
//方式2
int n1;
while ((n1 = fr.read()) != -1){
System.out.print((char) n1);//abc老师
}
//4.关闭流
fr.close();
}
}
循环读取
package io;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Test2 {
public static void main(String[] args) throws IOException {
//文件-》程序
//1.创建文件对象
File f = new File("C:\\Users\\1\\IdeaProjects\\1_project\\test.txt");
//2.利用fileReader找到文件
FileReader fr = new FileReader(f);
//3.读取-引入
char[] ch = new char[5];//缓冲数组
int len = fr.read(ch);//返回值是数组中的有效长度
while ( len != -1){
/*
//方式1
for(int i = 0; i < len; i++){
System.out.println(ch[i]);
}
*/
//方式2,将数组转为字符串
String str = new String(ch, 0, len);
System.out.print(str);
len = fr.read(ch);
}
//4.关闭流
fr.close();
}
}
FileWriter
程序-》文件 一个字符一个字符向外输出
package io;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Test3 {
public static void main(String[] args) throws IOException {
//有一个目标文件
File f = new File("C:\\Users\\1\\IdeaProjects\\1_project\\test1.txt");
//2.FileWriter写文件
FileWriter fw = new FileWriter(f,true);//true是在源文件上追加写入,false是覆盖
//3.开始输出
String str = "helloworld";
for(int i = 0; i < str.length(); i++){
fw.write(str.charAt(i));
}
//关闭流
fw.close();
}
}
利用缓冲数组向外输出
package io;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Test3 {
public static void main(String[] args) throws IOException {
//有一个目标文件
File f = new File("C:\\Users\\1\\IdeaProjects\\1_project\\test1.txt");
//2.FileWriter写文件
FileWriter fw = new FileWriter(f,true);//true是在源文件上追加写入,false是覆盖
//3.开始输出
String str = "你好中国";
char[] chars = str.toCharArray();//利用数组一次写入多个字符
fw.write(chars);
//关闭流
fw.close();
}
}
package io;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Test4 {
public static void main(String[] args) throws IOException {
File f1 = new File("C:\\Users\\1\\IdeaProjects\\1_project\\test.txt");
File f2 = new File("C:\\Users\\1\\IdeaProjects\\1_project\\demo.txt");
FileReader fr = new FileReader(f1);
FileWriter fw = new FileWriter(f2);
//开始动作
/*
//1.一个一个读
int n = fr.read();
while (n!=-1){
fw.write(n);
n = fr.read();
}
*/
//2.利用缓冲数组读取
char[] chars = new char[5];
int len = fr.read(chars);
while (len != -1){
fw.write(chars, 0, len);
len = fr.read(chars);
}
//关闭流的时候倒着来,后用先关
fw.close();
fr.close();
}
}
FileInputStream
package io2;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Test1 {
public static void main(String[] args) throws IOException {
//利用字节流将文件内容读到程序中来
File f = new File("C:\\Users\\1\\IdeaProjects\\1_project\\lol.JPG");
FileInputStream fis = new FileInputStream(f);
int count = 0;//计入读入的字节个数
int n = fis.read();
while (n != -1){
count++;
System.out.println(n);
n = fis.read();
}
System.out.println(count);
fis.close();
}
}
package io2;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Test2 {
public static void main(String[] args) throws IOException {
//利用字节流将文件内容读到程序中来
File f = new File("C:\\Users\\1\\IdeaProjects\\1_project\\lol.JPG");
FileInputStream fis = new FileInputStream(f);
byte[] b = new byte[1024*7];
int len = fis.read(b);//len指的就是读取的数组中的有效长度
while (len != -1){
for(int i=0; i < len; i++){
System.out.println(b[i]);
}
len = fis.read();
}
fis.close();
}
}
FileOutputStream
package io2;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test3 {
public static void main(String[] args) throws IOException {
File f = new File("C:\\Users\\1\\IdeaProjects\\1_project\\lol.JPG");
File f2 = new File("C:\\Users\\1\\IdeaProjects\\1_project\\lol2.JPG");
FileInputStream fis = new FileInputStream(f);
FileOutputStream fos = new FileOutputStream(f2);
/*
//读一个字节,写一个字节
int n = fis.read();
while (n != -1){
fos.write(n);
n = fis.read();
}
*/
//利用缓冲数组
byte[] bytes = new byte[1024*7];//自定义长度
int len = fis.read();
while (len != -1){
fos.write(bytes, 0, len);
len = fis.read(bytes);
}
fos.close();
fis.close();
}
}
BufferedInputStream
BufferedOutputStream
处理流,缓冲字节流
package io2;
import java.io.*;
public class Test4 {
public static void main(String[] args) throws IOException {
File f = new File("C:\\Users\\1\\IdeaProjects\\1_project\\lol.JPG");
File f2 = new File("C:\\Users\\1\\IdeaProjects\\1_project\\lol2.JPG");
FileInputStream fis = new FileInputStream(f);
FileOutputStream fos = new FileOutputStream(f2);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] bytes = new byte[1024*7];
int len = bis.read(bytes);
while (len != -1){
bos.write(bytes, 0, len);
len = bis.read(bytes);
}
//如果处理流包裹着节点流,那么关闭高级的处理流就可以了
bos.close();
bis.close();
//fos.close();
//fis.close();
}
}
BufferReader
BufferWriter
缓冲字符流
package io2;
import java.io.*;
public class Test5 {
public static void main(String[] args) throws IOException {
File f = new File("C:\\Users\\1\\IdeaProjects\\1_project\\test.txt");
File f2 = new File("C:\\Users\\1\\IdeaProjects\\1_project\\test1.txt");
FileReader fis = new FileReader(f);
FileWriter fos = new FileWriter(f2);
BufferedReader br = new BufferedReader(fis);
BufferedWriter bw = new BufferedWriter(fos);
/*
//1.一个字符一个字符读取
int n = br.read();
while (n != -1){
bw.write(n);
n = br.read();
}
//2.利用缓冲数组
char[] chars = new char[30];
int len = br.read(chars);
while (len != -1){
bw.write(chars);
len = br.read(chars);
}
*/
//3.读取String
String str = br.readLine();//每次读取文本文件中一行,然后返回值字符串
while (str != null){
bw.write(str);
bw.newLine();//读一行进行换行
str = br.readLine();
}
bw.close();
br.close();
}
}
InputStreamReader
字节输入流-》字符输入流
OutputStreamWriter
字符输出流-》字节输出流
package io2;
import com.sun.org.apache.xpath.internal.operations.String;
import java.io.*;
import java.util.Arrays;
public class Test6 {
public static void main(java.lang.String[] args) throws IOException {
File f = new File("C:\\Users\\1\\IdeaProjects\\1_project\\test.txt");
File f2 = new File("C:\\Users\\1\\IdeaProjects\\1_project\\demo.txt");
FileInputStream fis = new FileInputStream(f);
//将字节转为字符时,需要指定编码格式
InputStreamReader isr = new InputStreamReader(fis,"utf-8");
FileOutputStream fos = new FileOutputStream(f2);
OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk");//gbk是中文字节码
char[] chars = new char[20];
int len = isr.read(chars);
while (len != -1){
osw.write(chars, 0, len);
len = isr.read(chars);
}
osw.close();
isr.close();
}
}
System.in
package io3;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) throws IOException {
/*
InputStream in = System.in;
int n = in.read();
System.out.println(n);
*/
Scanner sc = new Scanner(new FileInputStream(new File("C:\\Users\\1\\IdeaProjects\\1_project\\test.txt")));
while (sc.hasNext()){
System.out.println(sc.next());
}
}
}
System.out
package io3;
import java.io.PrintStream;
public class Test2 {
public static void main(String[] args) {
PrintStream out = System.out;
out.println("test");
System.out.println("test1");//这里和上面2行代码是一个意思
}
}
案例-键盘录入写进文件
package io3;
import java.io.*;
public class Test3 {
public static void main(String[] args) throws IOException {
InputStream in = System.in;
//字节流-》字符流
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
File f = new File("C:\\Users\\1\\IdeaProjects\\1_project\\test.txt");
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
String str = br.readLine();
while (!str.equals("exit")){
bw.write(str);
bw.newLine();
str = br.readLine();
}
bw.close();
br.close();
}
}
DataInputStream 将文件中存储的数据类型字符串写入内存的变量中
package io4;
import java.io.*;
public class Test1 {
public static void main(String[] args) throws IOException {
/*
File f = new File("C:\\Users\\1\\IdeaProjects\\1_project\\test.txt");
FileOutputStream fos = new FileOutputStream(f);
DataOutputStream dos = new DataOutputStream(fos);
*/
DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File("C:\\Users\\1\\IdeaProjects\\1_project\\test.txt")));
dos.writeUTF("你好");
dos.writeBoolean(false);
dos.writeDouble(1.2);
dos.close();
}
}
文件中写出来的类型程序才能读懂
DataOutputStream
将内存中的基本数据类型和字符串的变量写出文件中
package io4;
import java.io.*;
public class Test2 {
public static void main(String[] args) throws IOException {
DataInputStream dis = new DataInputStream(new FileInputStream(new File("C:\\Users\\1\\IdeaProjects\\1_project\\test.txt")));
System.out.println(dis.readUTF());//对应的读取类型必须跟写出的类型一致
System.out.println(dis.readBoolean());
System.out.println(dis.readDouble());
dis.close();
}
}
对象流
ObjectInputStream
package io5;
import java.io.*;
public class Test1 {
public static void main(String[] args) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("C:\\Users\\1\\IdeaProjects\\1_project\\test.txt")));
oos.writeObject("你好");
oos.close();
}
}
ObjectOutputStream
package io5;
import java.io.*;
public class Test2 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("C:\\Users\\1\\IdeaProjects\\1_project\\test.txt")));
String s = (String)(ois.readObject());
System.out.println(s);//你好
ois.close();
}
}
序列化
序列化:将内存的Java对象转换成和平台无关的二进制数据,从而允许把这种二进制数据持久地保留在磁盘上, 或通过网络将这种二进制数据传输到另一个网络节点上
package io6;
import java.io.Serializable;
public class Person implements Serializable {//类必须实现 Serializable接口,才具备序列化和反序列化能力
}
package io6;
import java.io.*;
public class Test1 {
public static void main(String[] args) throws IOException {
Person p = new Person();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("C:\\Users\\1\\IdeaProjects\\1_project\\test.txt")));
oos.writeObject(p);
oos.close();
}
}
反序列化
反序列化:当其他程序获取了这种二进制数据,就可以恢复成原来地Java对象
package io6;
import java.io.*;
public class Test2 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("C:\\Users\\1\\IdeaProjects\\1_project\\test.txt")));
Person p = (Person)(ois.readObject());
System.out.println(p);//io6.Person@45ee12a7
ois.close();
}
}
序列号serialVersionUID
package io6;
import java.io.Serializable;
//在Person类中加入序列化版本号之后,写出的时候才能tostring输出类的属性
public class Person implements Serializable {
private final static long serialVersionUID = 123L;
int age;
String name;
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
package io6;
import java.io.*;
public class Test2 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("C:\\Users\\1\\IdeaProjects\\1_project\\test.txt")));
Person p = (Person)(ois.readObject());
System.out.println(p);//Person{age=0, name='null'}
ois.close();
}
}
Idea中配置序列化版本号
被序列化类的内部的所有属性必须是可序列化的 static,transient修饰的属性不可以被序列化
网络编程
InetAddress
封装了IP
package inetAddress;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Test {
public static void main(String[] args) throws UnknownHostException {
//InetAddress ia = new InetAddress();//不能直接创建对象,InetAddress被default修饰了
InetAddress ia = InetAddress.getByName("10.187.102.77");
InetAddress ia1 = InetAddress.getByName("localhost");
System.out.println(ia);///10.187.102.77
System.out.println(ia1);//localhost/127.0.0.1
InetAddress ia2 = InetAddress.getByName("A156G0L58DZ6M2W");//计算机名
System.out.println(ia2);//A156G0L58DZ6M2W/192.168.0.101
System.out.println(ia.getHostName());//获取域名
System.out.println(ia.getHostAddress());//获取地址
}
}
InetSocketAddress
封装了IP,端口号
package inetAddress;
import java.net.InetAddress;
import java.net.InetSocketAddress;
public class Test2 {
public static void main(String[] args) {
InetSocketAddress isa = new InetSocketAddress("127.0.0.1", 8080);//对IP和端口号进行封装
System.out.println(isa);
System.out.println(isa.getHostName());
System.out.println(isa.getPort());
InetAddress ia = isa.getAddress();
System.out.println(ia.getHostName());
System.out.println(ia.getHostAddress());
}
}
套接字Socket
应用层或者传输层的协议 例:客户端发送一句话到服务器 双向通信
package server_client;
import java.io.*;
import java.net.Socket;
public class TestClient {
public static void main(String[] args) throws IOException {
Socket s = new Socket("127.0.0.1", 8080);//创建套接字
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
//利用OutputStream向外发送数据,利用处理流写入数据DataOutputStream
dos.writeUTF("你好");
//接收客户端
InputStream is = s.getInputStream();
DataInputStream dis = new DataInputStream(is);
String str = dis.readUTF();
System.out.println("服务器对我说:" + str);
dis.close();
is.close();
dos.close();
os.close();
s.close();
}
}
package server_client;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TestServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(8080);
Socket s = ss.accept();//等待接收客户端的数据,什么时候接收到数据,什么时候向下执行,返回值是Socket
InputStream is = s.getInputStream();
DataInputStream dis = new DataInputStream(is);
String str = dis.readUTF();
System.out.println("客户端发来的数据为:" + str);
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("你好,我是服务器,我接收到你的请求了");
dos.close();
os.close();
dis.close();
is.close();
s.close();
ss.close();
}
}
对象传输流
package client_server;
import java.io.Serializable;
public class User implements Serializable {
private final static long serialVersionUID = 123453636L;
private String name;
private String pwd;
public String getName() {
return name;
}
public String getPwd() {
return pwd;
}
public void setName(String name) {
this.name = name;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public User(String name, String pwd) {
this.name = name;
this.pwd = pwd;
}
}
package client_server;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class TestClient {
public static void main(String[] args) throws IOException {
Socket s = new Socket("127.0.0.1", 8080);//创建套接字
//录入用户的账号和密码
Scanner sc = new Scanner(System.in);
System.out.println("请录入您的账号");
String name = sc.next();
System.out.println("请录入您的密码");
String pwd = sc.next();
User user = new User(name, pwd);
OutputStream os = s.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(user);
//接收客户端
InputStream is = s.getInputStream();
DataInputStream dis = new DataInputStream(is);
boolean b = dis.readBoolean();
if(b){
System.out.println("恭喜,登录成功");
}else {
System.out.println("对不起,登录失败");
}
dis.close();
is.close();
oos.close();
os.close();
s.close();
}
}
package client_server;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TestServer {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ServerSocket ss = new ServerSocket(8080);
Socket s = ss.accept();//等待接收客户端的数据,什么时候接收到数据,什么时候向下执行,返回值是Socket
InputStream is = s.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
User user = (User) (ois.readObject());
boolean flag = false;
if(user.getName().equals("娜娜")&& user.getPwd().equals("123")){
flag = true;
}
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("你好,我是服务器,我接收到你的请求了");
dos.close();
os.close();
ois.close();
is.close();
s.close();
ss.close();
}
}