Java常见类
1.main:
main方法:
- public:保证能够调用到
- static:保证外界调用无需创建对象
- void: jvm无需返回值
- String[] args: 可以传入 调用main方法时 可以传入实际参数
代码1分析:
2.String:
1)创建String的方法比较多:可以通过构造器创建、通过双引号创建、按照字节数组创建、按照代码点创建还可以按照字符串对象创建字符串对象。
2)对于String类中的方法也非常多,以下代码中列出部分常用方法:
代码2分析:
package com.mage.changyonglei;
/**
* String//创建
* @author 盛萌
*
*/
public class Sstring {
public static void main(String[] args) {
//String构造器
String str=new String();
System.out.println(str);
//通过字符串常量直接创建String对象
String str1="";
//比较
System.out.println(str==str1);
//按照字节数组创建字符串对象
byte[] byt=new byte[]{12,43,67,89,97};
String str2=new String(byt);
System.out.println(str2);
String str3=new String(byt,3,4);
System.out.println(str2);
//按照字符数组创建字符串对象
char[] ch=new char[]{'大','萌','哈',100};
String str4=new String(ch);
System.out.println(str4);
String str5=new String(ch,1,2);
System.out.println(str5);
//按照代码点创建字符串对象
int[] i=new int[]{23,13,43,45,46,57};
String str6=new String(i,1,2);
System.out.println(str6);
//按照字符串对象创建字符串对象
String str7 = new String("abc");
System.out.println(str7);
// 创建一个String对象
}
}
package com.mage.changyonglei;
import java.util.Arrays;
/**
* String常见用法
* @author 盛萌
*
*/
public class Sstring02 {
public static void main(String[] args) {
// 创建一个String对象
String str=new String("ashsbfjsbhrjendmdcnkj");
//charAt(int index);返回当前索引位置上的指定字符
char ch1=str.charAt(1);
System.out.println("ch1="+ch1);
//codePointAt(index)返回指定索引位置上元素的代码点
int num1=str.codePointAt(3);
System.out.println(num1);
//compareTo(String)比较两个字符串的大小
String str1=new String("ahrjendmdcnkj");
int n=str.compareTo(str1);
System.out.println(n);
//compareToIgronCase(String)
//比较两个字符串的大小(忽略大小写)
String str3="asdfg";
String str4="ASDFG";
int m= str3.compareToIgnoreCase(str4);
System.out.println(m);
//concat(String)拼接
str3=str3.concat(str4);
System.out.println(str3);
//copyValueOf(char[])
char[] ch2=new char[]{'a','s','d','d','d',100};
str4=String.copyValueOf(ch2);
System.out.println("拼接之后的结果是:"+str4);
str4=String.copyValueOf(ch2,1,2);
System.out.println("拼接之后的结果是:"+str4);
//endsWith是否以()结尾
String str5="assd.com";
boolean flag=str5.endsWith(".com");
System.out.println(flag);
//getBytes
byte[] byt1=str5.getBytes();
System.out.println(byt1);
//getChars();
char[] ch3=new char[10];
str.getChars(1, 3, ch3,1);
System.out.println("获取字符串的字符数组:"+Arrays.toString(ch3));
//indexOf() 在string中第一次出现的位置
String str7="asdf,dsf.sdff";
str7.indexOf(".");
System.out.println(".在string中第一次出现的位置是:"+str7);
//isEmpty()
System.out.println(str7.isEmpty());
//repleace
String str8="asd,cdfv.dsfd";
str8=str8.replace("a", "m");
System.out.println(str8);
//splite:
String[] str9=str8.split(",");
for(String s:str9){
System.out.println(s);
}
//subString
str8=str8.substring(3);
System.out.println(str8);
//大小写转换
String str10="asdf";
str10=str10.toUpperCase();
System.out.println(str10);
}
}
3.StringBuffer :
**可变的原因:**底层就是一个字符数组,动态数组
代码3分析:
package com.mage.changyonglei;
/**
* StringBuffer
* @author 萌
*
*/
public class StringBufferTest {
public static void main(String[] args) {
StringBuffer s=new StringBuffer();
System.out.println("创建的StringBuffer的容量为:"+s.capacity());
//添加
s.append(true);
s.append('a').append(3).append(3.4f);
System.out.println(s);
System.out.println(s.length());
s.insert(1, 5);
System.out.println(s);
}
}
4.StringBuilder:
1.StringBuilder和StringBuffer 都继承了AbstractStringBuilder
2.StringBuffer效率低于StringBuilder
3.StringBuffer安全性要高于StringBuilder
4.一般情况下使用StringBuilder
代码4分析:
public class Test05 {
public static void main(String[] args) {
// StringBuilder
StringBuilder sb = new StringBuilder();//构建16个长度的字符数组
//添加元素
sb.append("aasassd");
sb.insert(2, "dgdfbfdb");
System.out.println(sb);
}
}
5.String、StringBuffer、StringBuilder:
1.String类:代表字符串,其值在创建以后不可以更改;String中可以通过compareTo方法比较;
2.StringBuffer类:是可变的其底层就是一个动态字符数组;执行效率比StringBuilder要低,但是安全性要高;
3.StringBuilder类:也是可变的,和StringBuffer都继承了AbstractStringBuilder,执行效率比StringBuilder要高,但是安全性要低;一般情况下使用StringBuilder
6.Objects:
- isNull:判定对象是否为null
- toString:输出对象的
- requireNonNull 判定对象是否为null 如果是null则抛出空指针异常
代码5分析:
package com.mage.changyonglei;
import java.util.Objects;
/**
* Object
* @author 萌
*
*/
public class Object1 {
public static void main(String[] args) {
String str="acsdc";
if(!Objects.isNull(str)){
System.out.println(str.toString());
}
System.out.println(Objects.toString(str));
System.out.println(Objects.requireNonNull(str));
}
}
7.包装类:
8大基本数据类型 -> 8个包装类 :
byte->Byte
short->Short
char ->Character
int ->Integer
long ->Long
float->Float
double->Double
boolean->Boolean
jdk12 Integer中的所有构造器都过时 通过valueOf方法获取int对应的Integer对象
String->int Integer.parseInt();// 可能报异常
int ->String String.valueOf()
代码6分析:
public class Test01 {
public static void main(String[] args) {
//静态成员变量
System.out.println("BYTES:"+Integer.BYTES);
System.out.println("MAXVALUE:"+Integer.MAX_VALUE);
System.out.println("MINVALUE:"+Integer.MIN_VALUE);
System.out.println("SIZE:"+Integer.SIZE);
System.out.println("CLASS:"+Integer.TYPE);
//构造器
Integer in1 = new Integer(12);
System.out.println(in1);
Integer in2 = new Integer("123");// 可能出现数字格式化异常
System.out.println(in2);
System.out.println(Integer.max(12, 20));
//parseInt(String)
System.out.println("字符串转为int:"+Integer.parseInt("1234"));
System.out.println("字符串转为 int:"+Integer.parseInt("1100",2));// 将一个对应进制的数值变为对应十进制的字符串
System.out.println("2进制:"+Integer.toBinaryString(Integer.MAX_VALUE));
System.out.println("8进制:"+Integer.toOctalString(12));
//获取Integer对象
Integer in3 = Integer.valueOf(12);
System.out.println(in3);
Integer in4 = Integer.valueOf("12");
System.out.println(in4);
}
}
1.jdk1.5之后支持自动拆装箱,本质上就是调用了
2.装箱:Integer.valueOf()
3.拆箱:对象.intValue()
4.自动装箱时,首先会判定当前的值是否在缓冲区中[-128,127],如果再改区间中,直接从缓冲区中获取对应的Integer对象,反之会重新创建一个新的Integer对象.
代码图示1:
Boolean对象:
1.字面值创建Boolean对象时 只能指定true和false 并且创建的对象也是对应的true和false
2.字符串创建Boolean对象是 只要字符是true/false 无所谓大小写 得到对应的Boolean对象就是与之对应的true和false
3.其它所有字符串赋值都是false
代码7分析:
public class Test03 {
public static void main(String[] args) {
// 创建Boolean对象
Boolean f1 = new Boolean(true);
System.out.println(f1);
f1 = new Boolean(false);
System.out.println(f1);
f1 = new Boolean("1");
System.out.println(f1);
f1 = new Boolean("0");
System.out.println(f1);
f1 = new Boolean("TRue");
System.out.println(f1);
f1 = new Boolean("False");
System.out.println(f1);
f1 = new Boolean("123");
System.out.println(f1);
}
}
Date:
1.空构造器对象创建出的是当前系统时间对象
2.可以设置相应时间输出的格式
代码7分析:
public class Test01 {
public static void main(String[] args) {
//创建Date对象
Date d = new Date();
System.out.println(d);
//通过带参构造器创建对象
Date date = new Date(1563960432618L);
System.out.println(date);
System.out.println(d.after(date));
System.out.println(d.before(date));
//获取毫秒数
long dateTime = System.currentTimeMillis();
System.out.println(dateTime);
//创SimpleDateFormat对象
SimpleDateFormat sd = new SimpleDateFormat();
//设置一下输出的内容格式
sd.applyPattern("yyyy年MM月dd日 HH时mm分ss秒 是一年中的第D天 W w");
//调用格式化方法格式化日期
String str = sd.format(date);
System.out.println(str);
//创建对象并且指定格式化的内容
SimpleDateFormat ss = new SimpleDateFormat("yy/MM/dd hh:mm:ss");
System.out.println(ss.format(date));
}
}
8.Canlendar:
1).设置时间格式:可以创建SimpleDateFormat(“相应的格式参数”)进行设置;
2).Calendar.DATE:获取日历当前的天
3).Calendar.DATE_OF_MONTH:获取日历当前的天
4).Calendar.DAY_OF_WEEK:获取一周中的哪一天,周天是第一天
5).Calendar.MONTH:获取日历当前的月
6).setLenient(false):设置是否开启格式检查,默认情况下是关闭的;
7).add():传入参数在当前日期上进行累加,会继续增位,相当于这个月加完会增位到下个月继续累加;
8).roll():传入参数在当前日期上进行累加,不会继续增位,相当于这个月加完不会增位到下个月继续累加;
常见方法代码:
package com.mage.common.calender;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Test01 {
public static void main(String[] args) {
// 创建对象
Calendar c = Calendar.getInstance();
System.out.println(c);
Date d = new Date(11939345012L);
//定义日期格式
SimpleDateFormat sd = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
String str = sd.format( d);
System.out.println(str);
//获取当前日历中的天
System.out.println("获取当前日历中的天:"+c.get(Calendar.DATE));
System.out.println("获取当前日历中的天:"+c.get(Calendar.DAY_OF_MONTH));
//星期从星期天开始 星期天是第一天
System.out.println(c.get(Calendar.DAY_OF_WEEK));//星期从星期天开始 星期天是第一天
System.out.println(c.get(Calendar.MONTH));
}
}
public class Test02 {
public static void main(String[] args) {
//创建对象
Calendar c = Calendar.getInstance();
System.out.println(c);
//add 累加会增位
c.add(Calendar.DAY_OF_MONTH, 13);
//获取当前一个月的哪一天
System.out.println(c.get(Calendar.DAY_OF_MONTH));
//获取月份
System.out.println(c.get(Calendar.MONTH));
c = Calendar.getInstance();
//roll 不会增位
c.roll(Calendar.DAY_OF_MONTH, 13);
System.out.println(c.get(Calendar.DAY_OF_MONTH));
System.out.println(c.get(Calendar.MONTH));
System.out.println("===");
c = Calendar.getInstance();
c.setLenient(true);
c.set(Calendar.DAY_OF_MONTH, 32);
System.out.println(c.get(Calendar.DAY_OF_MONTH));
System.out.println(c.get(Calendar.MONTH));
}
}
日历的编写:
package com.mage.common;
import java.nio.charset.MalformedInputException;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
public class Calenders {
private int year;
private int month;
private int day;
static Calendar c=Calendar.getInstance();
public Calenders() {
this(c.get(Calendar.YEAR), 12, 12);
}
public Calenders(int year, int month, int day) {
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month-1);
c.set(Calendar.DAY_OF_MONTH, day);
}
public void print(){
Calendar c=Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month-1);
c.set(Calendar.DAY_OF_MONTH, day);
System.out.println("周天\t\t周\t\t一周\t\t二周\t\t三周四\t\t周五\t\t周六");
c.set(Calendar.DAY_OF_MONTH, 1);
int b=c.get(Calendar.DAY_OF_WEEK)-1;
for(int i=0;i<b;i++){
System.out.println("\t");
}
int days=c.getActualMaximum(Calendar.DAY_OF_MONTH);
for(int i=1;i<=days;i++){
if(day==c.get(Calendar.DAY_OF_MONTH)){
System.out.println("*");
}
if(c.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY) {
System.out.println();
}
c.set(Calendar.DAY_OF_MONTH, i+1);
}
}
public static void main(String[] args){
Calenders p=new Calenders();
p.print();
try{
TimeUnit.SECONDS.sleep(10000000);
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
9.File:
1)创建文件对象时不用在意当前路径或者是文件是否存在都会被创建出来;
2)File.pathSeparator:路径分隔符;
3)File.separator:路径分隔符;
4)canExecute():查看是否可执行
5)canWrite():查看是否可写
6)canRead():查看是否可读
7)compareTo():比较路径
8)getPath():获取路径
10)createNewFile():创建文件
11)getAbsolutePath():获取绝对路径
12)mkdir:只能创建一级目录
13)mkdirs:可以创建多级目录
常见方法代码:
package com.mage.file;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class Test02 {
public static void main(String[] args) {
// 创建对象
File f = new File("C:\\Users\\盛萌\\Desktop\\qq.txt");
System.out.println("查看是否可执行:"+f.canExecute());
System.out.println("查看是否可可写:"+f.canWrite());
System.out.println("查看是否可度:"+f.canRead());
File ff = new File("C:\\Users\\盛萌\\Desktop\\q.txt");
//比较的path
System.out.println(ff.compareTo(f));
// 获取路径
System.out.println(f.getPath());
try {
//创建文件 确保路径存在
System.out.println("创建文件是否成功:"+f.createNewFile());
}catch(IOException e) {
e.printStackTrace();
}
//downLoad();
System.out.println(ff.equals(f));
f = new File("ccc.txt");
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("是否是绝对路径:"+f.isAbsolute());
//获取绝对路劲
System.out.println("获取绝对路径:"+f.getAbsolutePath());
System.out.println("获取文件名称:"+f.getName());// 获取文件名称
System.out.println("获取父级目录:"+f.getParent());
System.out.println("获取相对路径(项目根目录):"+f.getPath());
f = new File("c:\\");
System.out.println("获取剩余大小:"+f.getFreeSpace());
System.out.println("获取总共大小:"+f.getTotalSpace());
System.out.println("获取可用大小:"+f.getUsableSpace());
System.out.println("是否是绝对路径:"+f.isAbsolute());
f = new File("C:\\Users\\盛萌\\Desktop\\qq.txt");
long l = f.lastModified();
Date d = new Date(l);
SimpleDateFormat sd = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
String str = sd.format(d);
System.out.println(new SimpleDateFormat("yyyy/MM/dd hh:mm:ss").format(new Date(l)));
System.out.println(f.length());
f = new File("c:\\");
String[] strs = f.list();
for(String st:strs) {
System.out.println(st);
}
System.out.println("===================");
File[] fs = f.listFiles();
for(File file:fs) {
System.out.println(file.getName()+"==="+file.length());
}
}
public static void downLoad() {
try {
File d = new File("C:\\Users\\盛萌\\Desktop\\qq.txt");
File temp = File.createTempFile("hanhanzhenghan",".avi",d);
TimeUnit.SECONDS.sleep(2);
temp.deleteOnExit();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
编写DIR:
package com.mage.file;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test04 {
public static void main(String[] args) {
//file对象
File file = new File("c:\\");
//获取当前file中的所有目录对象
File[] fs = file.listFiles();
int count=0,cou=0;
long len1=0;
//迭代所有file对象
for(File f:fs) {
String dateStr = new SimpleDateFormat("yyyy/MM/dd hh:mm").format(new Date(f.lastModified()));
String isDirectory=null;
String isFile=null;
if( f.isDirectory()){
isDirectory="<DIR>";
count++;
}else{
isDirectory="";
}
if(f.isFile()){
isFile=String.valueOf(f.length());
len1 += f.length();
cou++;
}else{
isFile = "";
}
String FileName = f.getName();
System.out.println(dateStr+"\t"+isDirectory+"\t"+isFile+"\t"+FileName);
}
System.out.println("\t\t"+cou+"\t\t"+len1);
System.out.println("\t\t"+count);
}
}
IO:
1)分类:
(1)按照输出的数据类型不同:字节流、字符流。
(2)按照流的方向:输入流、输出流
[外链图片转存失败(img-jK7Jzm68-1564061186141)(file:///C:\Users\盛萌\AppData\Local\Temp\ksohtml11664\wps1.jpg)]
(3)按照处理功能:节点流、处理流
[外链图片转存失败(img-a02fV8Ub-1564061186143)(file:///C:\Users\盛萌\AppData\Local\Temp\ksohtml11664\wps2.jpg)]
FileInputStream:
InputStream是所有字节流的父类
(1)FileInputStream:文件字节输入流,数据源在文件中,读取按照字节读取,流的方向是输入;
(2)用.read()读取数据时一次只能读取一个字节,读取到文件末尾,返回-1;也可以在read(设置读取的字节数组名)读取字节数组。
(3)FileInputStream创建要保证文件存在。
代码8分析:
package com.mage.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class Test01 {
public static void main(String[] args) throws IOException {
//创建对象
InputStream tn=new FileInputStream("C:\\Users\\盛萌\\Desktop\\qq.txt");
//读取数据
int bit =tn.read();
//输出数据
System.out.println("读取到的数据:"+(char)bit);
//关闭连接
tn.close();
}
}
循环读取:
package com.mage.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class Test02 {
public static void main(String[] args) throws IOException {
//创建对象
InputStream tn=new FileInputStream("C:\\Users\\盛萌\\Desktop\\qq.txt");
//循环读取数据
int num=0;
while((num=tn.read())!=-1){
System.out.println("读取的数据是"+num);
}
//关闭资源
tn.close();
}
}
多字节读取:
package com.mage.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class Test03 {
public static void main(String[] args) throws IOException {
InputStream tn=new FileInputStream("C:\\Users\\盛萌\\Desktop\\qq.txt");
byte[] byt=new byte[1024];
//读取一个字节数组长度的数据 返回读取到的字节数组的长度
int l=tn.read(byt);
//分析数据
String msg=new String(byt,0,l);
System.out.println(msg);
//关闭资源
tn.close();
}
}
FileOutputStream:
OutputStream:所有字节输出流的父类都是OutputStream;
(1)FileOutputStream:输出的目的地是文件,输出的类型是字节;输出时,如果文件不存在会创建该文件,但是不会创建目录;
(2)创建FileOutputStream对象时第二个参数boolean值说明是否在当前文件后追加内容,默认为false,不追加。
(3)write():写出数据;
(4)资源关闭顺序:先打开的后关闭
代码9分析:
package com.mage.io;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Test04 {
public static void main(String[] args) throws IOException {
//创建对象
OutputStream tn=new FileOutputStream("C:\\Users\\盛萌\\Desktop\\qq.txt");
//声明写出的数据
int num=97;
//写出数据
tn.write(num);
//关闭
tn.close();
}
}
复制粘贴实现:
package com.mage.io;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/*
*
* 先打开后关
*
*/
public class Test09 {
public static void main(String[] args) throws IOException {
CtrlCV();
}
private static void CtrlCV() throws IOException{
//1:声明复制和粘贴的文件对象
String srcFile1 = "C:\\Users\\meng\\Desktop\\wenjian\\peng";
String destFile1 = "123.jpg";
//2:声明对象
InputStream is = new FileInputStream(srcFile1);
OutputStream os = new FileOutputStream(destFile1);
//3:读取文件
int len = 0;
while((len=is.read())!=-1) {
//写出
os.write(len);
}
os.close();
is.close();
}
}