JAVA基础
1 、基本数据类型
Java内置8种基本类型
-> 4种整数类型: byte, short, int, long
-> 2种浮点类型: float, double
-> 1种布尔类型: boolean
-> 1种字符类型: char
原始数据类型对应的封装对象
- (byte, Byte), (short, Short), (long, Long), (float,Float), (double, Double), (boolean, Boolean)
- (int, Integer), (char, Character)
2.常量
- final:
- 修饰变量时,用以定义常量;
- 修饰方法时,方法不能被重写(Override);
- 修饰类时,类不能被继承。
- short s1=1; s1=s1+1;
这一句编译错误,因为执行s1+1返回的结果是int类型(执行隐式类型转换)。修改的话要强制转换为short型才可以。
3.数组
int[] arr1 = {1,2,3,4}; int[] arr2 = new int[4]; int[] arr3 = new int[]{1,2,3,4};
- 数组越界,抛出ArrayIndexOutOfBoundsException
- 数组具有length属性 注意:属性不是方法,不需要加()
- 如果不对数组指定初值,默认初始化为相应数据类型的默认值。
- 多维数组,嵌套中括号即可。
- 数组是一种特殊的结构,在数组对象的对象头中需要记录数组长度的信息
String类方法
1、替换字符
1 public String replace(char oldChar, char newChar)
2 //代码
3 String str="好家伙 123 321";
4 str=str.replace(" ","%20");
5 System.out.println(str);
6 //结果:
7 //好家伙%20123%20321
2、以特定字符分割字符串
注意:
1.如果用“.”作为分隔的话,必须是如下写法,String.split("\\."),这样才能正确的分隔开
2.如果用“|”作为分隔的话,必须是如下写法,String.split("\\|"),这样才能正确的分隔开
1 Scanner sc=new Scanner(System.in);
2 String str=sc.next()
3 String []chs1 = str.split("\\.")
4 System.out.println(Arrays.toString(chs1));
5
6 //输入192.168.1.1
7 //结果:
8 //["192","168","1","1"]
3.char数组转换为字符串
1 Ex:
2 char x[]={'l','s','g'};
3 String str =new String(x);
4 System.out.println(str);
5
6 //结果:"isg"
7
8 //如果使用Arrays.toString()
9 //字符串会以数组形式输出;
10 Ex:
11 char x[]={'l','s','g'};
12 String str=Arrays.toString(x);
13 System.out.println(str)
14 //结果为[l, s, p] 一个String类型的数组
4、转换大小写
toLowerCase() toUpperCase()
5、字符串的拼接有几种?分别是?、
1.用“+”直接拼接
2.用String的concat()方法进行拼接
6、“==”与equals (0bject类)方法之间的关系
//== //如果比较的是基本数据类型,则比较的是他们的内容是否相等, //如果比较的是引用数据类型,则比较的是他们的内存地址是否相同; //Object中的equals()方法 //作用和== 相同,但是一般对于引用数据类型我们会重写equals方法 //.Java中String和基本数据类型的包装类型都重写了equals()方法, //使得他们比较的是两个对象的内容是否相等.
7、判断字符串中是否包含所给char
String.continus("所给char值")
8、常用方法
//找到字符第一次出现的位置: Str.indexOf("内容")
//最后一次出现的位置: Str.lastIndexOf("内容")
//替换字符: Str.replace("旧内容","新内容")
//查找以什么开头: Str.startsWith("内容")
//查找以什么结尾: Str.endsWith("内容")
//返回指定索引处的 char 值 Str.charat("下标")
//将字符从此字符串复制到目标字符数组 str.getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
//当且仅当 length() 为 0 时返回 true str.isEmpty();
//返回此字符串的长度 str.length();
//将此字符串转换为一个新的字符数组。 str.toCharArray();
//返回字符串的副本,忽略前导空白和尾部空白 str.trim();
//用下标截取一段字符串 str.subString("开始下标","结束下标")
StringBuffer
1、构造方法
StringBuffer sb=new StringBuffer(String str)
2、 将指定的(字符串、char、char 数组....)追加到此字符序列。
char 数组....sb.append('内容');
3、移除此序列的子字符串中的字符。
delete(int start, int end)
4、移除此序列指定位置的 char。
deleteCharAt(int index)
5、将数组参数 str 的子数组的字符串表示形式插入此序列中(其他插入类似)
public StringBuffer insert(int index,
char[] str,
int offset,
int len)
参数:
index - 要插入子数组中的位置。
str - 一个 char 数组。
offset - 将插入子数组中的第一个 char 的索引。
len - 将插入子数组中的 char 的数量。
6、将此字符序列用其反转形式取代。
sb.reverse()
Integer类
1、十进制转二进制方法
Intager.tobinaryString("十进制数字")
2、其他进制转十进制方法
Intager.parseInt("内容",内容为几进制)
3、将字符串参数作为有符号的十进制整数进行解析
parseInt(String s)
4、返回一个表示该 Integer 值的 String 对象。
integer.toString()
date类
1、摒弃但还会用的方法
Date date = new Date();
date.getDate()
date.getMonth();
//特别注意.getTime()类型为long
date.getTime();
date.getYear();
2、日期表示
Date date = new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
//当前时间
String date1=sdf.format(date)
//转换日期类型
Date date2= sdf.parse(date1);
例题:
1、获取当前对象的日期的150天前的日期
public static void main(String[] args) throws ParseException {
Date date = new Date();
//特别注意.getTime()类型为long
date.setTime(date.getTime()-(150L *24*60*60*1000));
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
String a=sdf.format(date);
System.out.println(a);
}
2、有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为三天
public static void main(String[] args) throws ParseException {
String scstart=ScannerTools.getStr("请输入开始日期!");
String scend=ScannerTools.getStr("请输入结束日期!");
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date s = sdf.parse(scstart);
Date e = sdf.parse(scend);
long aaa=(e.getTime()-(long) s.getTime())/1000/60/60/24;
if (aaa == 1) {
System.out.println("两个日期是连续的我们规定他们之间的天数为三天");
}else {
System.out.println("相邻" + aaa + "天");
}
}
3、计算你出身多少天了
public static void main(String[] args) {
Date date=new Date() ;
Date date01=new Date() ;
long time01=date.getTime();
//System.out.println(time01);
//System.out.println(7836/36);
String yy=ScannerTools.getStr("请输入您的出生日期:");
String[] ss = yy.split("-");
int YYYY=Integer.parseInt(ss[0]);
int MM=Integer.parseInt(ss[1]);
int DD=Integer.parseInt(ss[2]);
date01.setYear(YYYY-1900);
date01.setMonth(MM-1);
date01.setDate(DD);
long time02 = date01.getTime();
//System.out.println(time02);
long asd=(time01-time02)/1000/60/60/24;
System.out.println("您的出生了"+asd+"天");
}
File类
1、基本方法
File file= new File("地址");
g读取文件名称 file.getName();
文件路径 file.getPath();
文件绝对路径 file.gatAbsoultFile(); //file.getAbsoultPath
创建文件 file.creatNewFile();
删除文件 file.delete();
文件修改时间 file.getModified();
文件父路径 file.getParent();
返回文件及文件夹: file.list();
该文件或目录存在? file.exists();
2、实用
判断File对象是否文件夹: file.isDirectory(); 指定文件夹下所有的文件: file.listFile(File::isFile);
IO(流)
1、字节流
//1、输入流(FileInputStream)
public class InputStreamTest {
//输入流的创建
@Test
public void test01() throws FileNotFoundException {
File file = new File("/Users/songfengquan/Desktop/b.txt");
//创建字节流对象
InputStream is = new FileInputStream(file);
System.out.println(is);
InputStream is1 = new FileInputStream("/Users/songfengquan/Desktop/b.txt");
System.out.println(is1);
}
//read方法
//单个字节读取
@Test
public void test02() throws IOException {
//public int read() throws IOException
//译: 从此输入流中读取一个字节的数据。 如果尚未提供输入,此方法将阻止。
//数据的下一个字节,如果到达文件末尾 -1 。
InputStream is = new FileInputStream("/Users/songfengquan/Desktop/b.txt");
// int soure = is.read();
// soure = is.read();
// soure = is.read();
// soure = is.read();
// System.out.println((char) soure);
int len = -1;
byte[] bytes = new byte[0];
int count = 0 ;
while ((len = is.read())!= -1){
// System.out.println((char) len);
bytes = Arrays.copyOf(bytes,bytes.length + 1);
bytes[bytes.length - 1 ] = (byte) len;
count++;
}
System.out.println(bytes);
//首先要保证去读取地文件地字符集和eclipse的字符集一致
String str = new String(bytes);
System.out.println(str);
System.out.println(count);
is.close();
}
//read方法
//read(char[] b)读取(常用)
@Test
public void test03() throws IOException{
//public int read(byte[] b) throws IOException
//译: 从此输入流b.length最多b.length字节的数据读入一个字节数组。 此方法将阻塞,直到某些输入可用。
////数据的下一个字节,如果到达文件末尾 -1 。
InputStream is = new FileInputStream("/Users/songfengquan/Desktop/b.txt");
//定义一个字节数组
byte[] bys = new byte[1024];
int count = 0 ;
StringBuilder sb = new StringBuilder();
while ((is.read(bys)) != -1){
sb.append(new String(bys));
count++;
}
System.out.println(sb);
System.out.println(count);
is.close();
}
//使用字节流读取图片
@Test
public void test04() throws Exception {
//程序运行当前时间(单位毫秒)
long start = System.currentTimeMillis();
//所以的流当中如果需要读写非文本类的文件,建议使用字节流
InputStream is = new FileInputStream("/Users/songfengquan/Desktop/IMG_0076.JPG");
int len = -1;
byte[] bytes = new byte[2048];
StringBuilder sb = new StringBuilder();
while ((len = is.read(bytes)) != -1){
sb.append(new String(bytes));
}
// System.out.println(sb);
//释放资源
is.close();
//程序运行当前时间(单位毫秒)
long end = System.currentTimeMillis();
System.out.println(end - start);
}
//使用字节流读取图片错误示范
//单个字节读取
//jvm会崩
@Test
public void test05() throws Exception {
long start = System.currentTimeMillis();
//使用字节流读取图片
//所以的流当中如果需要读写非文本类的文件,建议使用字节流
InputStream is = new FileInputStream("/Users/songfengquan/Desktop/IMG_0076.JPG");
int len = -1;
byte[] bytes = new byte[2048];
StringBuilder sb = new StringBuilder();
while ((len = is.read()) != -1){
//sb.append(new String(bytes));
bytes = Arrays.copyOf(bytes,bytes.length + 1);
//sb.append(len);
bytes[bytes.length - 1 ] = (byte) len;
}
//System.out.println(sb);
//释放资源
is.close();
long end = System.currentTimeMillis();
System.out.println(end - start);
}
//跳过指定的字节数
@Test
public void test06() throws IOException{
//public long skip(long n) throws IOException
//译: 跳过并丢弃输入流中的n字节数据。
//此方法执行in.skip(n)
//返回:跳过的实际字节数,(如果我们跳过的字节数超出我们文件的大小,那么跳出就是实际的字节数)
InputStream is = new FileInputStream("/Users/songfengquan/Desktop/IMG_0076.JPG");
//首先跳过10000个字节数
long l = is.skip(10000000);
System.out.println(l);
int len = -1;
byte[] bytes = new byte[2048];
StringBuilder sb = new StringBuilder();
while ((len = is.read(bytes)) != -1){
sb.append(new String(bytes));
}
System.out.println(sb.length());
//释放资源
is.close();
}
}
//2、输出流(OutPutStream)
public class OutputStreamTest {
@Test
public void test01() throws IOException {
File file;
//覆盖写入--->这个写入的方式会把文件原有的数据进行覆盖,不建议使用
OutputStream os = new FileOutputStream("/Users/songfengquan/Desktop/a.txt");
//追加式写入--->这个写入的方式是在原有数据的基础上写入内容
// OutputStream os = new FileOutputStream("/Users/songfengquan/Desktop/a.txt",true);
//public void write(byte[] b) throws IOException
//译: 将指定字节数组中的 b.length个字节写入此文件输出流。
// os.write("中华人民共和国万岁,世界大团结万岁".getBytes());
//public void write(int b) throws IOException
//译: 将指定的字节写入此文件输出流。 实现了write的方法OutputStream 。
// os.write(55);
// os.write(65);
//public void write(byte[] b,int off,int len) throws IOException
//译: 将从偏移量 off开始的指定字节数组中的 len字节写入此文件输出流。
//参数1:需要写入的字节数组
//参数2:开始写入的索引
//参数3:写入的个数(长度)
os.write("中华人民共和国万岁,世界大团结万岁".getBytes(),0,9 * 3);
os.close();
System.out.println("写入成功");
}
}
实现复制粘贴
//(1)复制-存储-写入
//复制文件到...
@Test
public void test01() throws IOException {
File file =new File("C:\\Users\\86185\\Desktop\\5858.jpg");
long a=file.length();
byte[]bytes=new byte[(int) a];
InputStream is=new FileInputStream(file);
is.read(bytes) ;
File file1=new File("C:\\Users\\86185\\Desktop\\123.jpg");
OutputStream outputStream=new FileOutputStream(file1);
outputStream.write(bytes,0, bytes.length);
outputStream.close();
is.close();
System.out.println("复制成功");
}
//(2)边读边写
@Test
public void test01() throws Exception {
//创建一个输入流
InputStream is = new FileInputStream("C:\\Users\\86185\\Desktop\\5858.jpg");
//创建输出流
OutputStream os = new FileOutputStream("C:\\Users\\86185\\Desktop\\58.jpg");
int len = -1;
byte[] bytes = new byte[2048];
while ((len = is.read(bytes))!=-1){
if(len != 2048)
System.out.println(len);
os.write(bytes,0,len);
}
//释放资源
//在同时使用多个流的情况下我们释放资源,我们按照先开后关的原则
os.close();
is.close();
System.out.println("Copy Over");
}
2、字符流
//!!字符流的复制粘贴
public class lx02 {
//字符流的复制粘贴
private Reader reader;
private Writer writer;
@Before
public void before1() throws Exception{
//读(输入)
reader=new FileReader("C:\\Users\\86185\\Desktop\\Srdm\\sb.txt");
//写 (输出)
writer=new FileWriter("C:\\Users\\86185\\Desktop\\lx.txt",true);
}
@Test
public void lx01() throws Exception{
int len;
char[]chars=new char[1024];
while ((len=reader.read(chars))!=-1){
writer.write(chars,0,len);
}
System.out.println("Ok!!");
}
@After
public void after1() throws IOException {
writer.close();
reader.close();
}
}
3、缓存字节流(BufferedInputStream)
//—字节流复制粘贴
public class CopyTest {
private InputStream in ;
private BufferedInputStream bis;
private OutputStream out ;
private BufferedOutputStream bos;
@Before
public void init(){
//地址
String pathName = "/Users/songfengquan/Desktop/一百零五个男人和三个女人的故事.txt";
try {
File file;
//字节输入(读)
in = new FileInputStream(pathName);
//字节输出(写)
out = new FileOutputStream("a.txt");
//缓存输入(读)
bis = new BufferedInputStream(in);
//缓存输出 (写)
bos =new BufferedOutputStream(out);
}catch (Exception e){
System.out.println("字节缓冲流初始化失败");
}
}
@Test
public void test01() throws IOException{
int len = -1;
byte[] bytes = new byte[2048];
while ((len = bis.read(bytes)) != -1){
bos.write(bytes,0,len);
}
bos.flush();
}
@After
public void close(){
try {
if (bos != null)
bos.close();
if (out != null)
out.close();
if (bis != null)
bis.close();
if (in != null)
in.close();
}catch (Exception e){
System.out.println("资源关闭失败");
}
}
}
4、缓存字符流(BufferedInputStream)
public class lx01 {
private Reader reader;
private BufferedReader bufferedReader;
private Writer writer;
private BufferedWriter bufferedWriter;
@Before
public void start() throws Exception{
String pathName="C:\\Users\\86185\\Desktop\\score.txt";
//字符输入(读)
reader=new FileReader(pathName);
//字符缓存输入(读)
bufferedReader=new BufferedReader(reader);
//字符输出(写)
writer=new FileWriter("C:\\Users\\86185\\Desktop\\a.txt",true);
//字符缓存输出(写)
bufferedWriter=new BufferedWriter(writer);
}
@Test
public void lx01() throws Exception{
String str;
StringBuilder sb=new StringBuilder();
//如果bufferedReader.readLine() true 执行写
while ((str=bufferedReader.readLine())!=null){
sb.append(str+"\r\n");
bufferedWriter.write(str+"\r\n");
}
System.out.println(sb);
}
@Test
public void lx02() throws Exception{
int len;
char []chars=new char[1024];
StringBuilder stringBuilder=new StringBuilder();
while((len=bufferedReader.read(chars))!=-1){
stringBuilder.append(chars,0,len);
}
System.out.println(stringBuilder);
}
@After
public void after() throws Exception{
if(bufferedWriter!=null)
bufferedWriter.close();
if (writer!=null)
writer.close();
if (bufferedReader!=null)
bufferedReader.close();
if (reader!=null)
reader.close();
}
}
--序列化和反序列化
public class test01 {
private ObjectOutputStream oos;
private ObjectInputStream ois;
//序列化(写)
@Test
public void lx01() {
try {
oos=new ObjectOutputStream(new FileOutputStream("3.txt"));
oos.writeObject(new Student("张三",20,85.3));
oos.writeObject(new Student("李四",24,80.3));
oos.writeObject(new Student("王五",63,70.3));
oos.writeObject(new Student("赵六",85,60.3));
oos.writeObject(new Student("越七",98,89.3));
oos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
//反序列化(读)
@Test
public void lx02() {
try {
ois=new ObjectInputStream(new FileInputStream("3.txt"));
Student str;
while ((str= (Student) ois.readObject())!=null){
// System.out.println("姓名:"+str.getName()+" 年龄:"+str.getAge()+" 成绩"+str.getScore());
System.out.println(str.toString());
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

浙公网安备 33010602011771号