目录
- 1. JavaAPI(2020)
- 1.1 java.lang.Object
- 1.2 java.util.Scanner
- 1.3 java.lang.String
- 1.4 java.lang.StringBuffer
- 1.5 排序算法
- 1.6 查找算法
- 1.7 java.util.Arrays
- 1.8 基本数据类型及包装类型
- 1.9 java.lang.Integer
- 1.10 java.lang.Character
- 1.11 java.lang.Math
- 1.12 java.util.Random
- 1.13 java.lang.System
- 1.14 java.math.BigInteger
- 1.15 java.math.BigDecimal
- 1.16 java.util.Date
- 1.17 java.text.DateFormat
- 1.18 java.util.Calendar
- 1.19 java.io.File
- 1.20 java.io.FileOutputStream
- 1.21 java.io.FileInputStream
- 1.22 java.io.BufferedInputStream
- 1.23 java.io.BufferedOutputStream
- 1.24 码表
- 1.25 java.io.InputStreamReader
- 1.26 java.io.OutputStreamWriter
- 1.27 java.io.BufferedReader
- 1.28 java.io.BufferedWriter
- 1.29 java.io.FileReader
- 1.30 java.io.FileWriter
- 1.31 java.io.LineNumberReader
- 1.32 java.io.DataInputStream
- 1.33 java.io.DataOutputStream
- 1.34 java.io.ByteArrayOutputStream
- 1.35 java.io.ByteArrayInputStream
- 1.36 java.io.CharArrayReader
- 1.37 java.io.CharArrayWriter
- 1.38 java.io.PrintWriter
- 1.39 java.io.PrintStream
- 1.40 java.io.RandomAccessFile
- 1.41 java.io.SequenceInputStream
- 1.42 java.io.ObjectOutputStream
- 1.43 java.io.ObjectInputStream
- 1.44 java.util.Properties
1. JavaAPI(2020)
- Object类/Scanner类
- String类/StringBuffer类/StringBuilder类
- 数组高级和Arrays类
- 基本类型包装类(Integer,Character)
- 正则表达式(Pattern,Matcher)
- Math类/Random类/System类
- BigInteger类/BigDecimal类
- Date类/DateFromat类/Calendar类
- LineNumberReader
- 数据输入输出流
- 内存操作流
- 打印流
- 标准输入输出流
- 随机访问流
- 合并流
- 序列化流和反序列化流
- Properties
1.1 java.lang.Object
Object类是所有类的根类,所有类都直接或间接的继承自该类。
1.1.1 成员方法
- int hashCode(),返回该对象的哈希值。哈希值是对象的逻辑地址值,非物理地址值。
- Class getClass(),返回Object的运行时类对象,Class是一个类型,是字节码文件*.class。
- String toString(),返回对象的文本表现形式,如果没有重写由三部分组成,全路径+@+16进制逻辑内存地址值,System.out.println(此处默认调用.toString)。
- boolean equals(Object obj),首先判断地址值是否相同,如果不同则为false,不同的object重写后不一样,但是会挨个比较其中的值,如果值相同,则为true。
- protected void finalize(),对象无引用,回收该对象,方法需要重写。
- protected void clone(),克隆对象的地址和原地址不同,引用对象的地址和原地址相同。
1.1.2 Demo
package com.xzy.JavaAPI.java.lang.Object;
import java.util.Objects;
public class Student extends Object implements Cloneable {
private String name;
private Integer age;
public Student() {
}
public String getName() {
return name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
protected void finalize() throws Throwable {
super.finalize();
}
//Student中默认重写equals方法
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return Objects.equals(name, student.name) &&
Objects.equals(age, student.age);
}
//仿照重写equals方法
public boolean equals2(Object o) {
Student s = (Student) o;
if (this.name.equals(s.getName()) && this.age == s.getAge()) {
return true;
} else {
return false;
}
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public int hashCode() {
return super.hashCode();//默认方法
// return 10;//重写方法
}
//未重写toString
@Override
public String toString() {
return super.toString();
}
//源码方法
//public String toString() {
// return getClass().getName() + "@" + Integer.toHexString(hashCode());
//}
//仿照源码重写toString,作为普通方法调用
public String toString2() {
//Integer类的toHexString方法可以将10进制转换成16进制并以字符串返回
String str = Integer.toHexString(this.hashCode());//调用本类this可省略
return this.getClass().getName() + "@" + str;//调用本类this可省略
}
//自定义toString方法
public String toString3() {
return name + ":" + age;
}
}
package com.xzy.JavaAPI.java.lang.Object;
public class ObjectP {
public static void main(String[] args) throws Throwable {
//int hashCode()
Student s1 = new Student();
Student s2 = new Student();
int h1 = s1.hashCode();
int h2 = s2.hashCode();
System.out.println(h1);
System.out.println(h2);
System.out.println("----------1--------");
//Class getClass()
Class clazz1 = s1.getClass();
Class clazz2 = s2.getClass();
System.out.println(clazz1);
System.out.println(clazz2);
String name = clazz1.getName();
System.out.println(name);
System.out.println("-----------2-------");
//String toString()
String s3 = s1.toString();
String s4 = s2.toString();
String s5 = s2.toString2();
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
Student joshua = new Student("Joshua", 20);
System.out.println(joshua.toString3());
System.out.println("----------3--------");
//boolean equals(Object obj)
Student jack = new Student("Jack", 11);
Student ben = new Student("Ben", 12);
Student ben2 = new Student("Ben", 12);
Student mm=jack;
System.out.println(mm == jack);
System.out.println(ben == jack);
System.out.println(ben == ben2);
//***==在基本数据类型中比较的是值,在引用和对象中比较的是对象的逻辑内存地址
System.out.println(ben.equals(jack));
String hello1 = new String("hello");
String hello2 = new String("hello");
System.out.println(hello1.equals(hello2));//逻辑内存地址不一样,堆中的值一样。String继承自Object类并重写了equals方法,先比较内存地址值是否相等,再比较值是否相等。
System.out.println(hello1==hello2);//比较的是对象的逻辑内存地址值。
System.out.println(ben2.equals2(ben));
//void finalize();
jack.finalize();
//void clone();
//一个对象是否能克隆要看该对象是否实现了一个标记接口clonable
Student student1 = new Student();
Student student2 = student1;
//student1和student2是同一个对象,其中student2是student1的引用.
Object clone = student1.clone();
Student student3 = (Student) clone;
System.out.println(student3);
System.out.println(student1);
}
}
1.2 java.util.Scanner
1.2.1 构造方法
- Scanner(InputStream source)构造一个新的 Scanner,它生成的值是从指定的输入流扫描的。
1.2.2 成员方法
- String next(),有效字符前面有空格、tab、回车时next()会忽略,next()接收的字符串中不包含空格、tab、回车,next()以回车作为结束的标志。
- String nextLine(),可以接收空格、tab,以回车键作为结束的标志。
1.2.3 Demo
package com.xzy.JavaAPI.java.util.Scanner;
import java.util.Scanner;
public class ScannerP {
public static void main(String[] args) {
}
private static void partOne() {
Scanner scanner = new Scanner(System.in);
System.out.println("please input a number:");
if (scanner.hasNextInt()) {
String st = scanner.nextLine();
System.out.println(st);
}else {
System.out.println("error");
}
Scanner scanner1 = new Scanner(System.in);
System.out.println("请输入任意字符");
String next = scanner1.next();
System.out.println(next);
System.out.println("----------------------");
}
}
1.3 java.lang.String
1.3.1 构造方法
- String(byte[] bytes)通过使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String。
- String(byte[] bytes, int offset, int length)通过使用平台的默认字符集解码指定的 byte 子数组,构造一个新的 String。
- String(char[] value)分配一个新的 String,使其表示字符数组参数中当前包含的字符序列。
- String(char[] value, int offset, int count)分配一个新的 String,它包含取自字符数组参数一个子数组的字符。
- String(byte[] bytes, Charset charset)通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String。
1.3.2 成员方法
- boolean equals(Object anObject)将此字符串与指定的对象比较。
- boolean equalsIgnoreCase(String anotherString)将此 String 与另一个 String 比较,不考虑大小写。
- boolean contains(CharSequence s)当且仅当此字符串包含指定的 char 值序列时,返回 true。
- boolean startsWith(String prefix)测试此字符串是否以指定的前缀开始。
- boolean endsWith(String suffix)测试此字符串是否以指定的后缀结束。
- boolean isEmpty()当且仅当 length() 为 0 时返回 true。
- int length()返回此字符串的长度。
- char charAt(int index)返回指定索引处的 char 值。
- int indexOf(int ch)返回指定字符在此字符串中第一次出现处的索引。
- int indexOf(String str)返回指定子字符串在此字符串中第一次出现处的索引。
- int indexOf(int ch, int fromIndex)返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。
- int indexOf(String str, int fromIndex)返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。
- String substring(int beginIndex)返回一个新的字符串,它是此字符串的一个子字符串。
- String substring(int beginIndex, int endIndex)返回一个新字符串,它是此字符串的一个子字符串。
- byte[] getBytes()使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
- char[] toCharArray()将此字符串转换为一个新的字符数组。
- String toLowerCase()使用默认语言环境的规则将此 String 中的所有字符都转换为小写。
- String toUpperCase()使用默认语言环境的规则将此 String 中的所有字符都转换为大写。
- String concat(String str)将指定字符串连接到此字符串的结尾。
- static String valueOf(char[] data)返回 char 数组参数的字符串表示形式。
- static String valueOf(int i)返回 int 参数的字符串表示形式。
- static String valueOf(Object obj)返回Object参数的字符串表示形式。
- String replace(char old,char new)
- String replace(String old,String new)
- String trim()
- int compareTo(String str)
- int compareToIgnoreCase(String str)
- byte[] getBytes(String charsetName)使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
1.3.3 Demo
package com.xzy.JavaAPI.java.lang.String;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Date;
import java.util.Scanner;
import static java.lang.String.valueOf;
public class StringP {
public static void main(String[] args) {
}
private static void part22() {
String str1 = "中国";
byte[] bytes1 = str1.getBytes();
System.out.println(Arrays.toString(bytes1));
System.out.println(new String(str1));
String str2="abc";
byte[] bytes2 = str2.getBytes();
System.out.println(Arrays.toString(bytes2));
System.out.println(new String(str2));
byte[] bys={-28, -72, -83, -27, -101, -67};
try {
System.out.println(new String(bys, "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
byte[] gbks = "美国".getBytes("gbk");
System.out.println(new String(gbks, "gbk"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private static void part21() {
String str1 = "adasdadjavafffffffffosoagknlaskdjlfnblaskdfjava";
String findStr="java";
int count = 0;
int indexOf = str1.indexOf(findStr);
while (indexOf!=-1) {
count++;
int newIndex = indexOf + findStr.length();
str1=str1.substring(newIndex);
indexOf= str1.indexOf(findStr);
}
System.out.println("字符串出现的次数为:"+count);
}
private static void part20() {
StringBuilder stringBuilder = new StringBuilder("12345");
StringBuilder reverse = stringBuilder.reverse();
System.out.println(reverse.toString());
}
private static void part19() {
String str1 = "abcdefghijklmn12121212AAAAAAAAAAAAAA";
String substring1 = str1.substring(0, 3);
System.out.println(substring1);
String s = substring1.toUpperCase();
System.out.println(s);
}
private static void part18() {
String str1 = "abcdefghijklmn12121212AAAAAAAAAAAAAA";
StringBuilder num = new StringBuilder();
StringBuilder big = new StringBuilder();
StringBuilder small = new StringBuilder();
Integer numCount = 0;
Integer bigCount = 0;
Integer smallCount = 0;
char[] chars = str1.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] >= '0' && chars[i] <= '9') {
num.append(chars[i]);
numCount++;
} else if (chars[i] >= 'A' && chars[i] <= 'Z') {
big.append(chars[i]);
bigCount++;
} else if (chars[i] >= 'a' && chars[i] <= 'b') {
small.append(chars[i]);
smallCount++;
}
}
System.out.println(num.toString() + "\t出现了" + numCount + "次");
System.out.println(big.toString() + "\t出现了" + bigCount + "次");
System.out.println(small.toString() + "\t出现了" + smallCount + "次");
{
//清空
num = null;
big = null;
small = null;
numCount = null;
bigCount = null;
smallCount = null;
}
}
private static void part17() {
String str1 = "abcdefghijklmn";
char[] chars = str1.toCharArray();
for (char aChar : chars) {
System.out.print("[" + aChar + "]" + ",");
}
System.out.println();
for (int i = 0; i < str1.length(); i++) {
System.out.print("[" + str1.charAt(i) + "]" + ",");
}
}
private static void part16() {
String username = "admin";
String password = "admin";
StringBuilder log = new StringBuilder();
System.out.println("你只有三次机会输入用户名和密码");
for (int i = 1; i <= 3; i++) {
System.out.print("请输入用户名:");
Scanner scanner = new Scanner(System.in);
String usernameInput = scanner.nextLine();
log.append(new Date() + "\tusername" + usernameInput + "\n");
System.out.print("请输入密码:");
String passwordInput = scanner.nextLine();
log.append(new Date() + "\tpassword:" + passwordInput + "\n");
if (username.compareTo(usernameInput) == 0 && password.compareTo(passwordInput) == 0) {
//equals和compareTo好像一样,欢迎点评
System.out.println("login success");
part15();
System.out.println("系统登录日志:\n" + log);
log = null;//清空
break;
} else {
System.out.println("账号或者密码错误!" + "剩余次数" + (3 - i));
}
}
}
private static void part15() {
int j = (int) ((Math.random() * 100) + 1);
int count = 0;
while (true) {
count++;
System.out.println("我已经生成数字[1,100],请输入一个数字:");
Scanner scanner = new Scanner(System.in);
if (scanner.hasNextInt()) {
int i = scanner.nextInt();
if (i > j) {
System.out.println("你输入的数字大了");
} else if (i < j) {
System.out.println("你输入的数字小了");
} else {
System.out.println("猜中了" + i + "," + count + "次");
break;
}
} else {
System.out.println("格式不对,请输入一个int类型的数字!");
}
}
}
private static void part14() {
String str1 = "abcde";
String str2 = "abcde";
String str3 = "bbcde";
String str4 = "fghijkl";
String str5 = "abcdef";
String str6 = "Abcde";
Integer integer = Integer.valueOf(str4.charAt(0));
int compareTo = str1.compareTo(str2);
System.out.println(compareTo);
int i = str1.compareTo(str3);
System.out.println(i);
int j = str1.compareTo(str4);
System.out.println(j);
System.out.println(integer);
int i1 = str1.compareTo(str5);
System.out.println(i1);
int i2 = str6.compareToIgnoreCase(str1);
System.out.println(i2);
}
private static void part13() {
String str1 = "aaaaaaaaasdadadasdsfnkflsafnkalsdnjakldad";
String replace = str1.replace('a', 'k');
String replace1 = str1.replace("da", "II");
System.out.println(replace);
System.out.println(replace1);
String str2 = " adadaad dadadad ";
String trim = str2.trim();
System.out.println(trim);
}
private static void part12() {
char[] chars = {'a', 'b', 'c'};
String s = valueOf(chars);
String s1 = valueOf(10);
System.out.println(s);
System.out.println(s1.charAt(0));
System.out.println(s1.charAt(1));
String s2 = valueOf(new Demo());
System.out.println(s2);
}
private static void part11() {
String str1 = "aaa";
String str2 = "bbb";
String concat = str1.concat(str2);//concat只能拼接字符串,如果为null则空指针异常,加号可以拼接任意类型且一边为null不会报空指针异常。
System.out.println(concat);
}
private static void part10() {
String str1 = "woaixuejava";
byte[] bytes = str1.getBytes();
for (int i = 0; i < bytes.length; i++) {
System.out.print((char) bytes[i]);
}
System.out.println("---------------------");
char[] chars = str1.toCharArray();
for (int i = 0; i < chars.length; i++) {
System.out.print(chars[i]);
}
System.out.println("---------------------");
String s = str1.toUpperCase();
System.out.println(s);
String s1 = str1.toLowerCase();
System.out.println(s1);
}
private static void part9() {
String str1 = "abcdefghijklmn";
String substring1 = str1.substring(str1.indexOf('b'), str1.indexOf('f') + 1);
System.out.println(substring1);
}
private static void part8() {
String str1 = "abcdefgh";
String str2 = "cd";
System.out.println(str1.indexOf(str2));
int i = str1.indexOf(str2, 3);
System.out.println(i);
int a = str1.indexOf('a', 0);
System.out.println(a);
}
private static void part7() {
String str1 = "abcde";
String s = valueOf(str1.charAt(1));
System.out.println(s);
int a = str1.indexOf('a');
System.out.println(a);
}
private static void part6() {
String str1 = "abcde";
String str2 = valueOf(str1.charAt(0));
String str3 = valueOf(str1.charAt(str1.length() - 1));
System.out.println(str2);
System.out.println(str1.startsWith(str2));
System.out.println(str3);
System.out.println(str1.endsWith(str3));
String str4 = "";//str4为空
String str5 = null;//str5未指向任何物理逻辑地址,空引用
System.out.println(str4.isEmpty());
System.out.println(str5.isEmpty());
System.out.println("----");
System.out.println(str4.length());
System.out.println(str5.length());
}
private static void part5() {
String str1 = "abc";
String str2 = new String("Abc");
String str3 = "a";
System.out.println(str1.equals(str2));
System.out.println(str1.equalsIgnoreCase(str2));
System.out.println(str1.contains(str3));
}
private static void part4() {
String str1 = new String("sdadadad");
String str2 = new String("1111111111111");
String str3 = str1 + str2;
System.out.println(str3);
//1、一个变量字符串加常量之后的结果是变量
//2、字符串常量的值是不能改变的
//***变量和谁相加都是变量,两个常量相加才是常量
}
private static void part3() {
char[] chars = {'a', 'b', 'c'};
String s = new String(chars);
String s1 = new String(chars, 1, 2);
System.out.println(s);
System.out.println(s1);
}
public static void part2() {
byte[] bytes = {97, 99, 100};
String s = new String(bytes);
String s1 = new String(bytes, 1, 2);
System.out.println(s1);
System.out.println(s);
System.out.println(s.length());
System.out.println(s1.length());
}
private static void part1() {
String str1 = "abc";//字符串常量,常量放在常量池中的方法区
String str2 = new String("abc");//堆内存中
int length = str2.length();
System.out.println(str2);
System.out.println(length);
}
}
1.4 java.lang.StringBuffer
StringBuffer是带缓冲区的字符串,长度和内容可以改变。
StringBuffer线程是安全的,线程安全的优点是数据安全,缺点是效率低。
1.4.1 构造方法
- StringBuffer(int capacity)构造一个不带字符,但具有指定初始容量的字符串缓冲区。
- StringBuffer(String str)构造一个字符串缓冲区,并将其内容初始化为指定的字符串内容。
- StringBuffer()构造一个其中不带字符的字符串缓冲区,其初始容量为 16 个字符。
1.4.2 成员方法
- StringBuffer append(String str)将指定的字符串追加到此字符序列。
- StringBuffer insert(int offset,String str)将字符串插入此字符序列中。
- StringBuffer delelteChart(int index)移除此序列指定位置的 char。
- StringBuffer delete(int start,int end)移除此序列的子字符串中的字符。
- StringBuffer replace(int start.int end,String str)使用给定 String 中的字符替换此序列的子字符串中的字符。
- StringBuffer reverse()将此字符序列用其反转形式取代。
- String substring(int start)返回一个新的 String,它包含此字符序列当前所包含的字符子序列。
- String substring(int start,int end)返回一个新的 String,它包含此序列当前所包含的字符子序列。
1.4.3 Demo
package com.xzy.JavaAPI.java.lang.StringBuffer;
public class StringBufferP {
public static void main(String[] args) {
}
private static void part7() {
StringBuffer hellojava = new StringBuffer("hellojava");
String substring = hellojava.substring(3);
System.out.println(hellojava);
System.out.println(substring);
String substring1 = hellojava.substring(0, 5);
System.out.println(substring1);
System.out.println(hellojava);
}
private static void part6() {
StringBuffer hellojava = new StringBuffer("hellojava");
hellojava.reverse();
System.out.println(hellojava);
}
private static void part5() {
StringBuffer hellojava = new StringBuffer("hellojava");
hellojava.replace(0,5,"hasdasdadhhhh");
System.out.println(hellojava);
}
private static void part4() {
StringBuffer helloword = new StringBuffer("helloword");
helloword.deleteCharAt(0);
helloword.deleteCharAt(3);
helloword.delete(0,3);//包左不包右
System.out.println(helloword);
}
private static void part3() {
StringBuffer java = new StringBuffer("java");
StringBuffer hello = java.insert(0, "hello");
System.out.println(java);
System.out.println(hello);
char[] chars={'a','b','c'};
java.insert(0,chars,0,1);
System.out.println(java);
}
private static void part2() {
StringBuffer java = new StringBuffer("java");
StringBuffer hello = java.append("hello");
System.out.println(java.capacity());
System.out.println(hello.capacity());
System.out.println(java);
System.out.println(hello);
System.out.println(java == hello);
StringBuffer append = java.append(20);
System.out.println(java);
System.out.println(append);
StringBuffer append1 = java.append(true);
System.out.println(java);
System.out.println(append1);
}
private static void part1() {
StringBuffer stringBuffer = new StringBuffer();
int capacity = stringBuffer.capacity();
System.out.println(capacity);//字符缓冲区容量是缓冲区大小,容量可自动扩容
System.out.println(stringBuffer.length());//长度是字符缓冲区实际字符的个数
StringBuffer stringBuffer1 = new StringBuffer(20);
System.out.println(stringBuffer1.capacity());
System.out.println(stringBuffer1.length());
StringBuffer java = new StringBuffer("java");
System.out.println(java.capacity());
System.out.println(java.length());//默认容量16+
}
}
1.5 排序算法
1.5.1 冒泡排序
-
相邻元素两两比较,大的往后放,小的往前放,第一次完毕,最大值出现在了最大索引处。除最大元素外,剩余的元素以此类推。
-
外j内i,for循环0到对象的长度-1、-j-1,循环体为arr[i]>arr[i+1].if,int temp;temp=arr[i];arr[i]=arr[i+1];arr[i+1]=temp;
package com.xzy.JavaAPI.Arithmetic;
public class BinarySearch {
public static void main(String[] args) {} private static void characterSort() { String str1 = "jklmnabcdefghi"; char[] ch = str1.toCharArray(); int[] arr=new int[str1.length()]; for (int i = 0; i < ch.length; i++) { arr[i]=(int)ch[i]; } for (int j = 1; j < arr.length; j++) { for (int i = 0; i < arr.length - 1; i++) { if (arr[i] > arr[j]) { int temp; temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } } } for (int i = 0; i < arr.length; i++) { ch[i]=(char)arr[i]; } String s = String.valueOf(ch); System.out.println("排序后:"+s); } private static void binarySort() { int[] arr = getArr(); int[] num = new int[1]; if ((int) (Math.random() * 2 + 1) == 1) { num[0] = arr[(int) (Math.random() * 9 + 0)]; } else { num[0] = (int) (Math.random() * 1000 + 1); } System.out.println("我这次要猜的数字是:" + num[0]); int min = 0; int max = arr.length - 1; int mid = (min + max) / 2; while (true) { if (num[0] >= arr[min] && num[0] <= arr[max]) { if (num[0] > arr[mid]) { min = mid + 1; mid = (min + max) / 2; } else if (num[0] < arr[mid]) { max = mid - 1; mid = (min + max) / 2; } else if (num[0] == arr[mid]) { System.out.println("值找到了,数据的索引是" + mid); break; } } else { System.out.println("您查找的值不存在"); break; } } } private static int[] getArr() { int[] arr = GenerateRandomNumber(); for (int j = 1; j < arr.length; j++) { for (int i = 0; i < arr.length - 1; i++) { if (arr[i] > arr[j]) { int temp; temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } } } System.out.println("排序后:"); for (int i : arr) { System.out.print(i + ","); } System.out.println(); return arr; } private static int[] GenerateRandomNumber() { int[] arr = new int[10]; for (int i = 0; i < arr.length; i++) { arr[i] = (int) (Math.random() * 100 + 1); for (int j = 0; j < i; j++) { if (arr[i] == arr[j]) { i--; break; } } } System.out.println("生成的随机数为:"); for (int i : arr) { System.out.print(i + ","); } System.out.println(); return arr; }
}
1.5.2 选择排序
-
从最小索引开始,依次选择每个元素和其他所有的元素进行比较,小的放在小的索引处。
-
外j内i,外for循环1到对象长度,内for循环0到对象长度-1,循环体为arr[i]>arr[j].if,int temp;temp=arr[j];arr[j]=arr[i];arr[i]=temp;
package com.xzy.JavaAPI.Arithmetic;
public class SelectionSort {
public static void main(String[] args) {
int[] arr = GenerateRandomNumber();
for (int j = 1; j < arr.length; j++) {
for (int i = 0; i < arr.length-1; i++) {
if (arr[i]>arr[j]) {
int temp;
temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}
}
System.out.println(“排序后:”);
for (int i : arr) {
System.out.print(i+",");
}} private static int[] GenerateRandomNumber() { int[] arr = new int[10]; for (int i = 0; i < arr.length; i++) { arr[i]= (int) (Math.random() * 100 + 1); for (int j = 0; j < i; j++) { if (arr[i]==arr[j]) { i--; break; } } } System.out.println("生成的随机数为:"); for (int i : arr) { System.out.print(i+","); } System.out.println(); return arr; }
}
1.6 查找算法
1.6.1 基本查找
循环遍历某个值在某个对象中是否存在并返回索引
package com.xzy.JavaAPI.Arithmetic;
public class BasicSearch {
public static void main(String[] args) {
int[] arr1 = GenerateASetOfRandomNumbers();
int[] num = new int[1];
int[] index = new int[10];
num[0]=arr1[(int)(Math.random()*10+0)];
System.out.println("生成一个组中的数据为:\n"+num[0]);
for (int i = 0; i < arr1.length; i++) {
if (arr1[i]==num[0]) {
index[0]=i;
}
}
System.out.println("已查找到数据,位于原数组的第" + (index[0] + 1) + "个元素");
System.out.println("查找的数据值为:"+arr1[index[0]]);
}
private static int[] GenerateASetOfRandomNumbers() {
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (Math.random() * 100 + 1);
for (int j = 0; j < i; j++) {
if (arr[i] == arr[j]) {
i--;
break;
}
}
}
System.out.println("生成一组随机数为:");
for (int i : arr) {
System.out.print(i + ",");
}
System.out.println();
return arr;
}
}
1.6.2 二分查找
前提是数组是有序的
package com.xzy.JavaAPI.Arithmetic;
public class BinarySearch {
public static void main(String[] args) {
}
private static void characterSort() {
String str1 = "jklmnabcdefghi";
char[] ch = str1.toCharArray();
int[] arr=new int[str1.length()];
for (int i = 0; i < ch.length; i++) {
arr[i]=(int)ch[i];
}
for (int j = 1; j < arr.length; j++) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[j]) {
int temp;
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
for (int i = 0; i < arr.length; i++) {
ch[i]=(char)arr[i];
}
String s = String.valueOf(ch);
System.out.println("排序后:"+s);
}
private static void binarySort() {
int[] arr = getArr();
int[] num = new int[1];
if ((int) (Math.random() * 2 + 1) == 1) {
num[0] = arr[(int) (Math.random() * 10 + 0)];
} else {
num[0] = (int) (Math.random() * 1000 + 1);
}
System.out.println("我这次要猜的数字是:" + num[0]);
int min = 0;
int max = arr.length - 1;
int mid = (min + max) / 2;
while (true) {
if (num[0] >= arr[min] && num[0] <= arr[max]) {
if (num[0] > arr[mid]) {
min = mid + 1;
mid = (min + max) / 2;
} else if (num[0] < arr[mid]) {
max = mid - 1;
mid = (min + max) / 2;
} else if (num[0] == arr[mid]) {
System.out.println("值找到了,数据的索引是" + mid);
break;
}
} else {
System.out.println("您查找的值不存在");
break;
}
}
}
private static int[] getArr() {
int[] arr = GenerateRandomNumber();
for (int j = 1; j < arr.length; j++) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[j]) {
int temp;
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
System.out.println("排序后:");
for (int i : arr) {
System.out.print(i + ",");
}
System.out.println();
return arr;
}
private static int[] GenerateRandomNumber() {
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (Math.random() * 100 + 1);
for (int j = 0; j < i; j++) {
if (arr[i] == arr[j]) {
i--;
break;
}
}
}
System.out.println("生成的随机数为:");
for (int i : arr) {
System.out.print(i + ",");
}
System.out.println();
return arr;
}
}
1.7 java.util.Arrays
1.7.1 成员方法
- static int binarySearch(int[] a, int key)使用二分搜索法来搜索指定的 int 型数组,以获得指定的值。
- static String toString(short[] a)返回指定数组内容的字符串表示形式。
1.7.2 Demo
package com.xzy.JavaAPI.java.util.Arrays;
import java.util.Arrays;
public class ArraysP {
public static void main(String[] args) {
}
private static void part2() {
int[] arr = GenerateRandomNumber();
System.out.println(arr);
String s = Arrays.toString(arr);
System.out.println(s);
}
private static void part1() {
int[] arr = GenerateRandomNumber();
Arrays.sort(arr);
System.out.println("排序后的数据为:");
for (int i : arr) {
System.out.print(i+",");
}
System.out.println();
int index=arr[(int) (Math.random() * 10 + 0)];
System.out.println("查找的值为:"+index);
int i = Arrays.binarySearch(arr, index);
System.out.println("查找的索引为"+i);
}
private static int[] GenerateRandomNumber() {
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++) {
arr[i]= (int) (Math.random() * 100 + 1);
for (int j = 0; j < i; j++) {
if (arr[i]==arr[j]) {
i--;
break;
}
}
}
System.out.println("生成的随机数为:");
for (int i : arr) {
System.out.print(i+",");
}
System.out.println();
return arr;
}
}
1.8 基本数据类型及包装类型
- byte,Byte
- short,Short
- int,Integer
- long,Long
- float,Float
- double,Double
- char,Character
- boolean,Boolean
1.9 java.lang.Integer
1.9.1 构造方法
- Integer(int value)构造一个新分配的 Integer 对象,它表示指定的 int 值。
- Integer(String s)构造一个新分配的 Integer 对象,它表示 String 参数所指示的 int 值。
1.9.2 成员方法
- static String toString(int i, int radix)返回用第二个参数指定基数表示的第一个参数的字符串表示形式。
- static String toBinaryString(int i)以二进制(基数 2)无符号整数形式返回一个整数参数的字符串表示形式。
- static String toHexString(int i)以十六进制(基数 16)无符号整数形式返回一个整数参数的字符串表示形式。
- static String toOctalString(int i)以八进制(基数 8)无符号整数形式返回一个整数参数的字符串表示形式。
1.9.3 Demo
package com.xzy.JavaAPI.java.lang.Integer;
public class IntegerP {
public static void main(String[] args) {
}
private static void part6() {
//如果int是-128-127之间的话,java会从缓存池中拿,如果不是则会new一个对象new Integer(value)
Integer integer = new Integer(100);
Integer i=100;//Integer.valueOf(100)
i=i+1000;
System.out.println(integer);
System.out.println(i);
}
private static void part5() {
//2-36进制有效,0-9+a-z
int num=100;
String s = Integer.toString(num, 8);
System.out.println(s);
String s1 = Integer.toString(num, 2);
System.out.println(s1);
String s2 = Integer.toString(num, 20);
System.out.println(s2);
String s3 = Integer.toString(num, 100);
System.out.println(s3);
String s4 = Integer.toString(num, 50);
System.out.println(s4);
System.out.println("序号\t\t原值\t\t进制数\t\t转换值");
for (int i = 0; i < 50; i++) {
String s5 = Integer.toString(num, i);
System.out.println(i+"\t\t"+num+"\t\t"+i+"\t\t\t"+s5);
}
}
private static void part4() {
String s="100";
Integer integer = new Integer(s);
int i = integer.intValue();
System.out.println(i);
int i1 = Integer.parseInt(s);
System.out.println(i1);
}
private static void part3() {
//int-->String
int i=1000;
String str="";
str=i+str;
System.out.println(str);
Integer integer = new Integer(i);
System.out.println(integer.toString());
System.out.println(String.valueOf(i));
System.out.println(Integer.toString(i));
}
private static void part2() {
Integer integer = new Integer(100);
System.out.println(integer);
Integer integer1 = new Integer("1000");
System.out.println(integer1);
}
private static void part1() {
int i=1231231231;
int maxValue = Integer.MAX_VALUE;
int minValue = Integer.MIN_VALUE;
if (i>=minValue&&i<=maxValue) {
System.out.println(i+"在int范围内");
}else {
System.out.println(i+"超过int范围");
}
System.out.println("二进制:"+Integer.toBinaryString(i));
System.out.println("十六进制:"+Integer.toHexString(i));
System.out.println("十进制:"+Integer.toOctalString(i));
}
}
1.10 java.lang.Character
1.10.1 构造方法
- Character(char value)构造一个新分配的 Character 对象,用以表示指定的 char 值。
1.10.2 成员方法
- static boolean isUpperCase(char ch)确定指定字符是否为大写字母。
- static boolean isLowerCase(char ch)确定指定字符是否为小写字母。
- static boolean isDigit(char ch)确定指定字符是否为数字。
- static char toUpperCase(char ch)使用取自 UnicodeData 文件的大小写映射信息将字符参数转换为大写。
- static char toLowerCase(char ch)使用取自 UnicodeData 文件的大小写映射信息将字符参数转换为小写。
1.10.3 Demo
package com.xzy.JavaAPI.java.lang.Character;
public class CharacterP {
public static void main(String[] args) {
}
private static void part3() {
int big=0;
int small=0;
int num=0;
String s="abcdefABCD1233";
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (Character.isUpperCase(chars[i])) {
big++;
}else if(Character.isLowerCase(chars[i])){
small++;
}else if(Character.isDigit(chars[i])){
num++;
}
}
System.out.println("big:" + big);
System.out.println("small:" + small);
System.out.println("big:" + num);
}
private static void part2() {
boolean a = Character.isUpperCase('a');
System.out.println(a);
boolean b = Character.isLowerCase('b');
System.out.println(b);
boolean digit = Character.isDigit('9');
System.out.println(digit);
System.out.println(Character.toUpperCase('a'));
System.out.println(Character.toLowerCase('A'));
}
private static void part1() {
Character ch = new Character('a');
System.out.println(ch);
ch='b';//自动装箱
System.out.println(ch);
}
}
1.11 java.lang.Math
1.11.1 成员静态常量
- static double E 比任何其他值都更接近 e(即自然对数的底数)的 double 值。
- static double PI 比任何其他值都更接近 pi(即圆的周长与直径之比)的 double 值。
1.11.2 静态成员方法
- static double abs(double a)返回 double 值的绝对值。
- static double ceil(double a)返回最小的(最接近负无穷大)double 值,该值大于等于参数,并等于某个整数。
- static double floor(double a)返回最大的(最接近正无穷大)double 值,该值小于等于参数,并等于某个整数。
- static float max(float a, float b)返回两个 float 值中较大的一个。
- static double pow(double a, double b)返回第一个参数的第二个参数次幂的值。
- static double random()返回带正号的 double 值,该值大于等于 0.0 且小于 1.0。
- static int round(float a)返回最接近参数的 int。
- static double sqrt(double a)返回正确舍入的 double 值的正平方根。
1.11.3 Demo
package com.xzy.JavaAPI.java.lang.Math;
import java.util.Scanner;
public class MathP {
public static void main(String[] args) {
part3();
}
private static void part3() {
System.out.println("请输入随机数的起始值:");
Scanner scanner = new Scanner(System.in);
int start = scanner.nextInt();
System.out.println("请输入随机数的终止值:");
int end = scanner.nextInt();
int[] arr = new int[100];
System.out.println("序号\t\t数字");
for (int i = 0; i < 100; i++) {
arr[i] = (int) (Math.random() * (end - start + 1) + start);//[0,1)*200+100=[0,200)+100=[100,300)
System.out.println(i + "\t\t" + arr[i]);
}
}
private static void part2() {
double a = -2.054888887;
double abs = Math.abs(a);
System.out.println(abs);
System.out.println(Math.ceil(2.4879));
System.out.println(Math.floor(2.4879));
System.out.println(Math.max(2.5, 3.2));
System.out.println(Math.pow(2, 3));
System.out.println((int) (Math.random() * 100 + 1));
System.out.println(Math.round(3.49));
System.out.println(Math.sqrt(4));
}
private static void part1() {
double e = Math.E;
System.out.println(e);
double pi = Math.PI;
System.out.println(pi);
}
}
1.12 java.util.Random
1.12.1 构造方法
- Random()创建一个新的随机数生成器。种子是当前时间的毫秒值
- Random(long seed)使用单个 long 种子创建一个新的随机数生成器。 使用seed种子生产随机数
1.12.2 成员方法
- int nextInt()返回下一个伪随机数,它是此随机数生成器的序列中均匀分布的 int 值。
- void setSeed(long seed)使用单个 long 种子设置此随机数生成器的种子。
1.12.3 Demo
package com.xzy.JavaAPI.java.util.Random;
import java.util.Random;
import java.util.Scanner;
public class RandomP {
public static void main(String[] args) {
}
private static void part1() {
Random random = new Random();
for (int i = 0; i < 10; i++) {
int i1 = random.nextInt();
System.out.println(i1);
}
System.out.println();
for (int i = 0; i < 10; i++) {
System.out.println(random.nextInt());
}
for (int i = 0; i < 1000; i++) {
System.out.print(random.nextInt(100)+1+",");//[0,100)
}
}
private static void part2() {
Random random = new Random();
System.out.println("请输入随机数的起始值:");
Scanner scanner = new Scanner(System.in);
int start = scanner.nextInt();
System.out.println("请输入随机数的终止值:");
int end = scanner.nextInt();
int[] arr = new int[100];
System.out.println("序号\t\t数字");
for (int i = 0; i < 100; i++) {
arr[i] = (int) (random.nextInt(end-start+1)+start);//[0,1)*200+100=[0,200)+100=[100,300)
System.out.println(i + "\t\t" + arr[i]);
}
}
}
1.13 java.lang.System
1.13.1 静态方法
- static PrintStream err “标准”错误输出流。
- static InputStream in “标准”输入流。
- static PrintStream out “标准”输出流。
1.13.2 成员方法
- static void gc()运行垃圾回收器。
- System.gc()可用于垃圾回收。当使用System.gc()回收某个对象所占用的内存之前,通过要求程序调用适当的方法来 清理资源。在没有明确指定资源清理的情况下,
- Java提高了默认机制来清理该对象的资源,就是调用Object类的finallize()方法。finalize()方法的作用是释放一个对象占用的内存空间时,会被JVM调用。
- 而子类重写该方法,就可以清理对象占用的资源,该方法没有链式调用,所以必须手动实现。
- 从程序的运行结果可以发现,执行System.gc()前,系统会自动调用finallize()方法清除对象占有的资源,通过super.finalize()方式可以实现从下到上finalize()方法的调用,即先释放自己的资源,再去释放父类的资源。
- 但是,不要在程序中频繁的调用垃圾回收,因为每一次执行垃圾回收,jvm都会强制启动垃圾回收器运行,这会耗费更多的系统资源,会与正常的Java 程序运行争抢资源,
- 只有在执行大量的对象的释放,才能调用垃圾回收最好。
- static void exit(int status)终止当前正在运行的 Java 虚拟机。
0正常终止程序,非0非正常终止程序 - static long currentTimeMillis()返回以毫秒为单位的当前时间。
- static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。
1.13.3 Demo
package com.xzy.JavaAPI.java.lang.System;
public class Student {
private String name;
private Integer age;
public Student() {
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
protected void finalize() throws Throwable {
System.out.println("父类资源清理");
super.finalize();
}
}
package com.xzy.JavaAPI.java.lang.System;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
public class SystemP {
public static void main(String[] args) {
}
/**
* @Method {@link SystemP#readLinePra5}
* @Return {@link Void}
* @Description 字符缓冲流
* @Version 1.0
*/
public static void readLinePra5() {
InputStream keyboard = System.in;
BufferedReader br = new BufferedReader(new InputStreamReader(keyboard));
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(s);
}
public static void readPra4() {
InputStream keyboard = System.in;
try {
int read = keyboard.read();
System.out.println((char) read);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void part3() {
System.out.println(System.currentTimeMillis());
int[] arr1 = {1, 2, 3, 4, 5, 6};
int[] arr2 = {6, 7, 8, 9, 10};
System.out.println(Arrays.toString(arr2));
System.arraycopy(arr1, 2, arr2, 0, 2);
System.out.println(Arrays.toString(arr2));
}
private static void part2() {
System.out.println("程序将退出");
System.exit(0);
}
private static void part1() {
Student xzy = new Student("xzy", 20);
xzy = null;
System.gc();
}
}
1.14 java.math.BigInteger
1.14.1 构造方法
- BigInteger(String val)将BigInteger的十进制字符串表示形式转换为BigInteger。
1.14.2 成员方法
- BigInteger add(BigInteger val)返回其值为(this + val)的BigInteger。
- BigInteger subtract(BigInteger val)返回其值为(this - val)的BigInteger。
- BigInteger multiply(BigInteger val)返回其值为(this * val)的BigInteger。
- BigInteger divide(BigInteger val)返回其值为(this / val)的BigInteger。
- BigInteger[] divideAndRemainder(BigInteger val)返回包含(this / val)后跟(this % val)的两个BigInteger的数组。
1.14.3 Demo
package com.xzy.JavaAPI.java.math.BigInteger;
import java.math.BigInteger;
public class BigIntegerP {
public static void main(String[] args) {
}
private static void part3() {
BigInteger bigInteger = new BigInteger("10");
BigInteger bigInteger1 = new BigInteger("20");
BigInteger add = bigInteger.add(bigInteger1);
System.out.println(add);
BigInteger subtract = bigInteger.subtract(bigInteger1);
System.out.println(subtract);
BigInteger multiply = bigInteger.multiply(bigInteger1);
System.out.println(multiply);
BigInteger divide = bigInteger.divide(bigInteger1);
System.out.println(divide);
BigInteger[] bigIntegers = bigInteger.divideAndRemainder(bigInteger1);
System.out.println("----");
for (BigInteger integer : bigIntegers) {
System.out.println(integer);
}
}
private static void part2() {
BigInteger bigInteger = new BigInteger("214748364812121212");
System.out.println(bigInteger);
}
private static void part1() {
int maxValue = Integer.MAX_VALUE;
int minValue = Integer.MIN_VALUE;
System.out.println(maxValue);//2147483647
System.out.println(minValue);//-2147483648
Integer integer = new Integer(maxValue+1);//-2147483648
//Integer integer1 = new Integer("2147483648");//java.lang.NumberFormatException: For input string: "21474836481
//System.out.println(integer1);
System.out.println(integer);
}
}
1.15 java.math.BigDecimal
1.15.1 静态方法
- static int ROUND_CEILING接近正无穷大的舍入模式。 向上取整
- static int ROUND_FLOOR接近负无穷大的舍入模式。 向下取整
- static int ROUND_HALF_UP向“最接近的”数字舍入,如果与两个相邻数字的距离相等,则为向上舍入的舍入模式。四舍五入
1.15.2 构造方法
- BigDecimal(BigInteger val)将BigInteger转换为BigDecimal。
1.15.3 成员方法
- BigDecimal add(BigDecimal augend)返回一个 BigDecimal,其值为 (this + augend),其标度为 max(this.scale(), augend.scale())。
- BigDecimal subtract(BigDecimal subtrahend)返回一个 BigDecimal,其值为 (this - subtrahend),其标度为 max(this.scale(), subtrahend.scale())。
- BigDecimal multiply(BigDecimal multiplicand)返回一个 BigDecimal,其值为 (this × multiplicand),其标度为 (this.scale() + multiplicand.scale())。
- BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)返回一个 BigDecimal,其值为 (this / divisor),其标度为指定标度。
1.15.4 Demo
package com.xzy.JavaAPI.java.math.BigDecimal;
import java.math.BigDecimal;
public class BigDecimalP {
public static void main(String[] args) {
}
private static void part1() {
BigDecimal bigDecimal = new BigDecimal("0.999");
BigDecimal bigDecimal1 = new BigDecimal("1.22355554888");
BigDecimal add = bigDecimal.add(bigDecimal1);
System.out.println(add);
BigDecimal subtract = bigDecimal.subtract(bigDecimal1);
System.out.println(subtract);
BigDecimal multiply = bigDecimal.multiply(bigDecimal1);
System.out.println(multiply);
BigDecimal divide1 = bigDecimal.divide(new BigDecimal("2"), 3, BigDecimal.ROUND_HALF_UP);
BigDecimal divide2 = bigDecimal.divide(new BigDecimal("2"), 8, BigDecimal.ROUND_HALF_UP);
BigDecimal divide3 = bigDecimal.divide(new BigDecimal("2"), 3, BigDecimal.ROUND_CEILING);
BigDecimal divide4 = bigDecimal.divide(new BigDecimal("2"), 3, BigDecimal.ROUND_FLOOR);
System.out.println(divide1);
System.out.println(divide2);
System.out.println(divide3);
System.out.println(divide4);
}
}
1.16 java.util.Date
1.16.1 构造方法
- Date()分配 Date 对象并初始化此对象,以表示分配它的时间(精确到毫秒)。
- Date(long date)分配 Date 对象并初始化此对象,以表示自从标准基准时间(称为“历元(epoch)”,即 1970 年 1 月 1 日 00:00:00 GMT)以来的指定毫秒数。
1.16.2 成员方法
- long getTime()返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
- void setTime(long time)设置此 Date 对象,以表示 1970 年 1 月 1 日 00:00:00 GMT 以后 time 毫秒的时间点。
1.16.3 Demo
package com.xzy.JavaAPI.java.util.Date;
import java.util.Date;
public class DateP {
public static void main(String[] args) {
}
private static void part2() {
long start = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
System.out.println(i);
}
long end = System.currentTimeMillis();
long time = end - start;
System.out.println(time);
}
private static void part1() {
Date date = new Date();
System.out.println(date.toLocaleString());
Date date1 = new Date(1000);
System.out.println(date1.toLocaleString());
System.out.println(date.getTime());
System.out.println(date1.getTime());
date.setTime(100000);
System.out.println(date.toLocaleString());
long l = System.currentTimeMillis();
System.out.println(l);
System.out.println(new Date(l).toLocaleString());
}
}
1.17 java.text.DateFormat
1.17.1 构造方法
- protected DateFormat()创建一个新的 DateFormat。
1.17.2 成员方法
- Date parse(String source)从给定字符串的开始解析文本,以生成一个日期。
- String format(Date date)将一个 Date 格式化为日期/时间字符串。
1.17.3 Demo
package com.xzy.JavaAPI.java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtils {
private DateUtils(){}
public static String getDate(String str) throws ParseException {
String pattern="yyyy年MM月dd日HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String parse = simpleDateFormat.parse(str).toLocaleString();
return parse;
}
public static String getDate(String str,String pattern) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String parse = simpleDateFormat.parse(str).toLocaleString();
return parse;
}
public static String getString(Date date){
String pattern="yyyy年MM月dd日HH时mm分ss秒";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String format = simpleDateFormat.format(date);
return format;
}
public static String getString(Date date,String pattern){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String format = simpleDateFormat.format(date);
return format;
}
}
package com.xzy.JavaAPI.java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class DateFormatP {
public static void main(String[] args) throws ParseException {
}
private static void part4() throws ParseException {
System.out.println("请输入你的生日:");
Scanner scanner = new Scanner(System.in);
String birthday = scanner.nextLine();
SimpleDateFormat date = new SimpleDateFormat("yyyy年MM月dd日");
Date parse = date.parse(birthday);
long time = parse.getTime();
long currentTimeMillis = System.currentTimeMillis();
long l = currentTimeMillis - time;
long i = l / 1000 / 60 / 60 / 24;
System.out.println(i);
}
private static void part3() throws ParseException {
//工具类调用
System.out.println(DateUtils.getDate("2020年5月19日20:43:19"));
System.out.println(DateUtils.getString(new Date()));
System.out.println("请输入你的生日:");
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
String birthday = DateUtils.getDate(s, "yyyy年MM月dd日");
System.out.println(birthday);
}
private static void part2() throws ParseException {
String str="2020年5月19日20:12:20";
String pattern="yyyy年MM月dd日HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
System.out.println(simpleDateFormat.parse(str).toLocaleString());
}
private static void part1() {
String pattern="yyyy年MM月dd日HH时mm分ss秒";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
Date date = new Date();
String format = simpleDateFormat.format(date);
System.out.println(format);
}
}
1.18 java.util.Calendar
1.18.1 构造方法
- protected Calendar()构造一个带有默认时区和语言环境的 Calendar。
- protected Calendar(TimeZone zone, Locale aLocale)构造一个带有指定时区和语言环境的 Calendar。
1.18.2 成员方法
- static Calendar getInstance()使用默认时区和语言环境获得一个日历。
- int get(int field)返回给定日历字段的值。
- Date getTime()返回一个表示此 Calendar 时间值(从历元至现在的毫秒偏移量)的 Date 对象。
- long getTimeInMillis()返回此 Calendar 的时间值,以毫秒为单位。
- abstract void add(int field, int amount)根据日历的规则,为给定的日历字段添加或减去指定的时间量。
- void set(int year, int month, int date)设置日历字段 YEAR、MONTH 和 DAY_OF_MONTH 的值。
1.18.3 Demo
package com.xzy.JavaAPI.java.util.Calender;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class CalenderP {
public static void main(String[] args) {
}
private static void part4() {
Calendar in = Calendar.getInstance();
System.out.println("请输入一个年份:");
Scanner scanner = new Scanner(System.in);
int date = scanner.nextInt();
in.set(Calendar.YEAR,date);
in.set(Calendar.MONTH,2);
in.set(Calendar.DAY_OF_MONTH,1);
in.add(Calendar.DAY_OF_MONTH,-1);
int i = in.get(Calendar.DAY_OF_MONTH);
System.out.println(i);
}
private static void part3() {
Calendar in = Calendar.getInstance();
in.set(Calendar.YEAR,2010);
in.add(Calendar.YEAR,5);
in.add(Calendar.YEAR,-10);
Date time = in.getTime();
System.out.println(time.toLocaleString());
}
private static void part2() {
Calendar ca = Calendar.getInstance();
Date time = ca.getTime();
System.out.println(time.toLocaleString());
System.out.println(ca.getTimeInMillis());
}
private static void part1() {
Calendar instance = Calendar.getInstance();
ArrayList<Integer> in = new ArrayList<>();
in.add(instance.get(Calendar.YEAR));
in.add(instance.get(Calendar.MONTH));
in.add(instance.get(Calendar.DAY_OF_MONTH));
in.add(instance.get(Calendar.HOUR));
in.add(instance.get(Calendar.MINUTE));
in.add(instance.get(Calendar.SECOND));
in.add(instance.get(Calendar.WEEK_OF_MONTH));
in.add(instance.get(Calendar.DAY_OF_WEEK));
for (Integer integer : in) {
System.out.println(integer);
}
}
}
1.19 java.io.File
1.19.1 构造方法
- File(String pathname)通过将给定路径名字符串转换为抽象路径名来创建一个新File实例。
- File(File parent, String child)根据parent抽象路径名和child路径名字符串创建一个新File实例。
- File(String parent, String child)根据parent路径名字符串和child路径名字符串创建一个新File实例。
1.19.2 成员方法
- boolean isDirectory()测试此抽象路径名表示的文件是否是一个目录。
- boolean isFile()测试此抽象路径名表示的文件是否是一个标准文件。
- boolean exists()测试此抽象路径名表示的文件或目录是否存在。
- boolean canRead()测试应用程序是否可以读取此抽象路径名表示的文件。
- boolean canWrite()测试应用程序是否可以修改此抽象路径名表示的文件。
- boolean isHidden()测试此抽象路径名指定的文件是否是一个隐藏文件。
- String getAbsolutePath()返回此抽象路径名的绝对路径名字符串。
- String getPath()将此抽象路径名转换为一个路径名字符串。
- String getName()返回由此抽象路径名表示的文件或目录的名称。
- long length()返回由此抽象路径名表示的文件的长度。
- long lastModified()返回此抽象路径名表示的文件最后一次被修改的时间。
- String[] list()返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中的文件和目录。
- File[] listFiles()返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件。
1.19.3 Demo
package com.xzy.JavaAPI.java.io.File;
import java.io.File;
import java.io.IOException;
import java.util.Date;
/**
* File类方法
*/
public class FileP {
public static void main(String[] args) {
}
private static void part11() {
File a = new File("a");
File b = new File("b");
System.out.println(a.mkdir());
System.out.println(b.mkdir());
File file = new File("a\\aa.txt");
try {
System.out.println(file.createNewFile());
} catch (IOException e) {
e.printStackTrace();
}
try {
System.out.println(file.renameTo(new File("b\\bb.txt")));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(new File("b\\bb.txt").renameTo(new File("b\\cc.txt")));
System.out.println(new File("a").renameTo(new File("dd")));
}
private static void part10() {
/**
* 分析
* 1.创建测试文件
* 2.获取文件夹下文件的父路径
* 3.获取文件夹下文件的名称
* 4.对父路径和文件名称拼接构成旧file对象,对文件名称+"1"拼接父路径构建新的file对象
* 5.旧.renameto(新)
*
*/
try {
System.out.println(new File("aa\\bb").mkdirs());
System.out.println(new File("aa\\bb\\a.txt").createNewFile());
System.out.println(new File("aa\\bb\\b.txt").createNewFile());
System.out.println(new File("aa\\bb\\c.txt").createNewFile());
System.out.println("------------创建完成-----------------");
} catch (IOException e) {
e.printStackTrace();
}
File[] files = new File("aa\\bb").listFiles();
for (File file : files) {
if (file.isFile()) {
String parent = file.getParent();
String name = file.getName();
String startName = name.substring(0, 1);
int endPoint = name.lastIndexOf(".");
String endName = name.substring(endPoint);
String newStartName = startName + "k";
System.out.println(file.renameTo(new File(parent + "\\"+newStartName + endName)));
System.out.println(new File(parent + "\\" + newStartName + endName));
}
}
try {
System.out.println(new File("aa\\bb\\ck.txt").delete());
System.out.println(new File("aa\\bb\\ak.txt").delete());
System.out.println(new File("aa\\bb\\bk.txt").delete());
System.out.println(new File("aa\\bb").delete());
System.out.println(new File("aa").delete());
System.out.println("------------删除完成-----------------");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void part9() {
part8();
String[] list = new File("aa\\bb").list();
for (String s : list) {
System.out.println(s);
}
for (String s : list) {
if (s.endsWith(".txt")) {
System.out.println(s);
}
}
File[] files = new File("aa\\bb").listFiles();
for (File file : files) {
String name = file.getName();
if (name.endsWith(".txt")) {
System.out.println(file.getName());
}
}
delete();
}
private static void part8() {
try {
create();
System.out.println("=====================================================");
String[] list = new File("aa\\bb").list();
for (String s : list) {
System.out.println(s);
}
File[] files = new File("aa\\bb").listFiles();
for (File file : files) {
System.out.println(file);
System.out.println(file.getAbsolutePath());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("------------------------------------");
delete();
}
}
private static void create() {
try {
System.out.println(new File("aa\\bb").mkdirs());
System.out.println(new File("aa\\bb\\a.txt").createNewFile());
System.out.println(new File("aa\\bb\\b.txt").createNewFile());
System.out.println(new File("aa\\bb\\c.txt").createNewFile());
System.out.println(new File("aa\\bb\\cc").mkdir());
} catch (IOException e) {
e.printStackTrace();
}
}
private static void delete() {
System.out.println(new File("aa\\bb\\a.txt").delete());
System.out.println(new File("aa\\bb\\b.txt").delete());
System.out.println(new File("aa\\bb\\c.txt").delete());
System.out.println(new File("aa\\bb\\cc").delete());
System.out.println(new File("aa\\bb").delete());
System.out.println(new File("aa").delete());
}
private static void part7() {
try {
System.out.println(new File("a.txt").createNewFile());
System.out.println(new File("b.txt").createNewFile());
System.out.println(new File("a.txt").getAbsolutePath());
System.out.println(new File("src\\main\\java\\com\\xzy\\JavaAPI\\Note\\JavaAPI.md").getAbsolutePath());
System.out.println(new File("b").getPath());
long l = new File("b.txt").lastModified();
Date date = new Date(l);
System.out.println(date.toLocaleString());
System.out.println(new File("a.txt").getName());
System.out.println(new File("b.txt").length());
} catch (IOException e) {
e.printStackTrace();
} finally {
new File("a.txt").delete();
new File("b.txt").delete();
}
}
private static void part6() {
try {
File aa = new File("aa");
File bb = new File("bb");
File cc = new File("cc.txt");
System.out.println(aa.mkdir());
System.out.println(bb.mkdir());
System.out.println(cc.createNewFile());
System.out.println("================================");
System.out.println(aa.isDirectory());
System.out.println(bb.isFile());
System.out.println(cc.isFile());
System.out.println("================================");
System.out.println(aa.exists());
System.out.println(bb.exists());
System.out.println(cc.exists());
System.out.println("================================");
System.out.println(aa.canRead());
System.out.println(bb.canRead());
System.out.println(cc.canRead());
System.out.println("================================");
System.out.println(aa.canWrite());
System.out.println(bb.canWrite());
System.out.println(cc.canWrite());
System.out.println("================================");
System.out.println(aa.isHidden());
System.out.println(bb.isHidden());
System.out.println(cc.isHidden());
} catch (IOException e) {
e.printStackTrace();
}
}
private static void part5() {
File file = new File("b.txt");
boolean b = file.renameTo(new File("a.txt"));
System.out.println(b);
}
private static void part4() {
try {
File aa = new File("aa");
boolean newFile1 = aa.createNewFile();
File file = new File("a.txt");
boolean newFile = file.createNewFile();
File aaa = new File("aaa\\bbb");
File aaa1 = new File("aaa");
boolean mkdir = aaa.mkdirs();
System.out.println(newFile1);
System.out.println(newFile);
System.out.println(mkdir);
System.out.println("----------------------------------");
System.out.println(aa.delete());
System.out.println(file.delete());
System.out.println(aaa.delete());
System.out.println(aaa1.delete());
} catch (IOException e) {
e.printStackTrace();
}
}
private static void part3() {
try {
File file = new File("C:\\Users\\xzy\\Desktop\\aa");
boolean mkdir = file.mkdir();
File file1 = new File("C:\\Users\\xzy\\Desktop\\bb\\cc");
boolean mkdir1 = file1.mkdir();
boolean mkdirs = file1.mkdirs();
File aaa = new File("aaa");
boolean mkdir2 = aaa.mkdir();
System.out.println(mkdir);
System.out.println(mkdir1);
System.out.println(mkdirs);
System.out.println(mkdir2);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void part2() {
try {
File file = new File("C:\\Users\\xzy\\Desktop\\aa.txt");
boolean newFile = file.createNewFile();
File file1 = new File("C:\\Users\\xzy\\Desktop\\test.txt");
boolean newFile1 = file1.createNewFile();
File file2 = new File("bb.txt");
boolean newFile2 = file2.createNewFile();
File file3 = new File("C:\\Users\\xzy\\Desktop\\test.txt");
boolean newFile3 = file3.createNewFile();
System.out.println(newFile);
System.out.println(newFile1);
System.out.println(newFile2);
System.out.println(newFile3);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void part1() {
File file = new File("C:\\Users\\xzy\\Desktop\\test.txt");
File file1 = new File("C:\\Users\\xzy\\Desktop", "test.txt");
File file2 = new File("C:\\Users\\xzy\\Desktop");
File file3 = new File(file2, "test.txt");
}
}
1.20 java.io.FileOutputStream
1.20.1 构造方法
- FileOutputStream(File file)创建一个向指定 File 对象表示的文件中写入数据的文件输出流。
- FileOutputStream(String name)创建一个向具有指定名称的文件中写入数据的输出文件流。
- FileOutputStream(File file, boolean append)创建一个向指定 File 对象表示的文件中写入数据的文件输出流。
- FileOutputStream(String name, boolean append)创建一个向具有指定 name 的文件中写入数据的输出文件流。
1.20.2 成员方法
- void write(byte[] b)将 b.length 个字节从指定 byte 数组写入此文件输出流中。
- void write(byte[] b, int off, int len)将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此文件输出流。
- void write(int b)将指定字节写入此文件输出流。
- void close()关闭此文件输出流并释放与此流有关的所有系统资源。
1.20.3 Demo
package com.xzy.JavaAPI.java.io.FileOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
public class FileOutputStreamP {
public static void main(String[] args) {
}
private static void part5() {
/**
* 标准IO写法
*/
FileOutputStream fileOutputStream=null;
try {
fileOutputStream=new FileOutputStream("b.txt",true);
fileOutputStream.write("\nxzy".getBytes());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void part4() {
try {
FileOutputStream fileOutputStream = new FileOutputStream("b.txt",true);
fileOutputStream.write("\ntest".getBytes());
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void part3() {
try {
FileOutputStream fileOutputStream = new FileOutputStream("b.txt",false);
fileOutputStream.write("test".getBytes());
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void part2() {
try {
FileOutputStream fileOutputStream = new FileOutputStream("b.txt");
String data="hello";
byte[] bytes = data.getBytes();
System.out.println(Arrays.toString(bytes));
fileOutputStream.write(97);
fileOutputStream.write(98);
fileOutputStream.write(99);
fileOutputStream.write(bytes);
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void part1() {
try {
FileOutputStream fileOutputStream = new FileOutputStream("a.txt");
String data="hello";
byte[] bytes = data.getBytes();
System.out.println(Arrays.toString(bytes));
fileOutputStream.write(bytes);
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void deleteFiles() {
System.out.println(new File("a.txt").delete());
System.out.println(new File("b.txt").delete());
}
}
1.21 java.io.FileInputStream
1.21.1 构造方法
- FileInputStream(File file)通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的 File 对象 file 指定。
- FileInputStream(String name)通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的路径名 name 指定。
1.21.2 成员方法
- int read()从此输入流中读取一个数据字节。
- int read(byte[] b)从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。
- int read(byte[] b, int off, int len)从此输入流中将最多 len 个字节的数据读入一个 byte 数组中。
1.21.3 Demo
package com.xzy.JavaAPI.java.io.FileInputStream;
import java.io.*;
import java.util.Arrays;
public class FileInputStreamP {
public static void main(String[] args) {
}
private static void part5() {
//测试
File file = new File("b.txt");
System.out.println(file.getAbsolutePath());
System.out.println(file.getPath());
System.out.println(file.getParent());
System.out.println(file.getName());
}
private static void part4() {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream("b.txt");
fileOutputStream = new FileOutputStream("c.txt");
//自定义字节读取写入
byte[] bys = new byte[1024];
int len;
while ((len = fileInputStream.read(bys)) != -1) {
fileOutputStream.write(bys, 0, len);
}
//单字节读取写入
//int data;
//while ((data = fileInputStream.read()) != -1) {
// fileOutputStream.write(data);
//}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void part3() {
/**
* 读取自定义字节个数
*/
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream("b.txt");
byte[] bys = new byte[11];
int len = fileInputStream.read(bys, 0, 11);
System.out.println(len);
System.out.println(Arrays.toString(bys));
System.out.println(new String(bys, 0, 11));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void part2() {
/**
* 读取自定义字节个数
*/
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream("b.txt");
byte[] bys = new byte[1024];
int len;
while ((len = fileInputStream.read(bys)) != -1) {
System.out.print(new String(bys, 0, len));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void part1() {
/**
* 读取一个字节
*/
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream("b.txt");
int b;
while (-1 != (b = fileInputStream.read())) {
System.out.print((char) b);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1.22 java.io.BufferedInputStream
1.22.1 构造方法
- BufferedInputStream(InputStream in)创建一个 BufferedInputStream 并保存其参数,即输入流 in,以便将来使用。
1.22.2 成员方法
- int read()参见 InputStream 的 read 方法的常规协定。
- int read(byte[] b, int off, int len)从此字节输入流中给定偏移量处开始将各字节读取到指定的 byte 数组中。
- void reset()参见 InputStream 的 reset 方法的常规协定。
1.22.3 Demo
package com.xzy.JavaAPI.java.io.BufferedInputStream;
import java.io.*;
public class BufferedInputStreamP {
public static void main(String[] args) {
}
private static void part2() {
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try {
bis=new BufferedInputStream(new FileInputStream("a.png"));
bos=new BufferedOutputStream(new FileOutputStream("b.png"));
byte[] bys = new byte[1024];
int len;
while ((len = bis.read(bys)) != -1) {
bos.write(bys,0,len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void part1() {
FileInputStream fis = null;
FileOutputStream fos=null;
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try {
fis=new FileInputStream("b.txt");
fos=new FileOutputStream("c.txt",true);
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//单字节读取
// int data;
// while ((data = bis.read()) != -1) {
// bos.write(data);
// }
//自定义字节读取
byte[] bys = new byte[1024];
int len;
while ((len = bis.read(bys)) != -1) {
bos.write(bys,0,len);
}
System.out.println("读取写入完成");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bos.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1.23 java.io.BufferedOutputStream
1.23.1 构造方法
- BufferedOutputStream(OutputStream out)创建一个新的缓冲输出流,以将数据写入指定的底层输出流。
1.23.2 成员方法
- void flush()刷新此缓冲的输出流。
- void write(byte[] b, int off, int len)将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此缓冲的输出流。
- void write(int b)将指定的字节写入此缓冲的输出流。
1.24 码表
- ASCII:占1个字节,只用了1个字节中的7位进行编码,还有一位是符号位,没有中文编码,存储2^7=128位字符
- Unicode:ASCII的升级,占用2个字节,Java就是使用的Unicode编码
- IOS-8859-1:占用1个字节,拉丁文编码,没有汉字
- GB2312\GBK\GB18030:2个字节,有中文编码
1.25 java.io.InputStreamReader
1.25.1 构造方法
- InputStreamReader(InputStream in, String charsetName)创建使用指定字符集的 InputStreamReader。
- InputStreamReader(InputStream in)创建一个使用默认字符集的 InputStreamReader。
1.25.2 成员方法
- int read()读取单个字符。
- int read(char[] cbuf, int offset, int length)将字符读入数组中的某一部分。
- void close()关闭该流并释放与之关联的所有资源。
1.25.3 Demo
package com.xzy.JavaAPI.java.io.InputStreamReader;
import java.io.*;
public class InputStreamReaderP {
public static void main(String[] args) {
FileInputStream fis=null;
FileOutputStream fos=null;
InputStreamReader isr=null;
OutputStreamWriter osw=null;
try {
fis = new FileInputStream("a.txt");
fos=new FileOutputStream("b.txt");
isr = new InputStreamReader(fis);
osw=new OutputStreamWriter(fos);
//单字符读取
// int data;
// while ((data = isr.read()) != -1) {
// System.out.print((char) data);
// }
//自定义字符读取
char[] cha = new char[1024];
int len;
while ((len = isr.read(cha)) != -1) {
System.out.println(cha);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
osw.close();
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1.26 java.io.OutputStreamWriter
1.26.1 构造方法
- OutputStreamWriter(OutputStream out)创建使用默认字符编码的 OutputStreamWriter。
- OutputStreamWriter(OutputStream out, String charsetName)创建使用指定字符集的 OutputStreamWriter。
1.26.2 成员方法
- void close()关闭此流,但要先刷新它。
- void flush()刷新该流的缓冲。
- String getEncoding()返回此流使用的字符编码的名称。
- void write(char[] cbuf, int off, int len)写入字符数组的某一部分。
- void write(int c)写入单个字符。
- void write(String str, int off, int len)写入字符串的某一部分。
1.27 java.io.BufferedReader
1.27.1 构造方法
- BufferedReader(Reader in)创建一个使用默认大小输入缓冲区的缓冲字符输入流。
- BufferedReader(Reader in, int sz)创建一个使用指定大小输入缓冲区的缓冲字符输入流。
1.27.2 成员方法
- void close()关闭该流并释放与之关联的所有资源。
- void mark(int readAheadLimit)标记流中的当前位置。
- boolean markSupported()判断此流是否支持 mark() 操作(它一定支持)。
- int read()读取单个字符。
- int read(char[] cbuf, int off, int len)将字符读入数组的某一部分。
- String readLine()读取一个文本行。
- boolean ready()判断此流是否已准备好被读取。
- void reset()将流重置到最新的标记。
- long skip(long n)跳过字符。
1.27.3 Demo
package com.xzy.JavaAPI.java.io.BufferedReader;
import java.io.*;
public class BufferedReaderP {
public static void main(String[] args) {
FileOutputStream fos = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
FileInputStream fis=null;
InputStreamReader isr=null;
BufferedReader bd=null;
try {
fos = new FileOutputStream("a.txt");
osw = new OutputStreamWriter(fos);
bw = new BufferedWriter(osw);
fis=new FileInputStream("b.txt");
isr=new InputStreamReader(fis);
bd=new BufferedReader(isr);
//测试
// for (int i = 0; i < 10; i++) {
// bw.write("hahahaa"+i);
// bw.newLine();
// }
// bw.flush();
//每次读一行
String str=null;
while ((str = bd.readLine()) != null) {
bw.write(str);
bw.newLine();
}
bw.flush();
//单字符读取
// int len;
// while ((len = bd.read()) != -1) {
// bw.write(len);
// }
//自定义字符读取
// char[] chs = new char[1024];
// int len;
// while ((len = bd.read(chs)) != -1) {
// bw.write(chs,0,len);
// }
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bw.close();
bd.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1.28 java.io.BufferedWriter
1.28.1 构造方法
- BufferedWriter(Writer out)创建一个使用默认大小输出缓冲区的缓冲字符输出流。
- BufferedWriter(Writer out, int sz)创建一个使用给定大小输出缓冲区的新缓冲字符输出流。
1.28.2 成员方法
- void close()关闭此流,但要先刷新它。
- void flush()刷新该流的缓冲。
- void newLine()写入一个行分隔符。
- void write(char[] cbuf, int off, int len)写入字符数组的某一部分。
- void write(int c)写入单个字符。
- void write(String s, int off, int len)写入字符串的某一部分。
1.29 java.io.FileReader
1.29.1 构造方法
- FileReader(File file)在给定从中读取数据的 File 的情况下创建一个新 FileReader。
- FileReader(FileDescriptor fd)在给定从中读取数据的 FileDescriptor 的情况下创建一个新 FileReader。
- FileReader(String fileName)在给定从中读取数据的文件名的情况下创建一个新 FileReader。
1.29.2 成员方法
- void close()关闭此流,但要先刷新它。
- void flush()刷新该流的缓冲。
- void newLine()写入一个行分隔符。
- void write(char[] cbuf, int off, int len)写入字符数组的某一部分。
- void write(int c)写入单个字符。
- void write(String s, int off, int len)写入字符串的某一部分。
1.29.3 Demo
package com.xzy.JavaAPI.java.io.FileReader;
import java.io.*;
public class FileReaderP {
public static void main(String[] args) {
BufferedReader br=null;
BufferedWriter bw=null;
try {
br=new BufferedReader(new FileReader("a.txt"));
bw=new BufferedWriter(new FileWriter("b.txt"));
//单字符读取
// int len;
// while ((len = br.read()) != -1) {
// bw.write(len);
// }
//自定义字符读取
// char[] chs = new char[1024];
// int len;
// while ((len = br.read(chs)) != -1) {
// bw.write(chs,0,len);
// }
//一行一行读取
String str=null;
while ((str = br.readLine()) != null) {
bw.write(str);
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
if (bw != null) {
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1.30 java.io.FileWriter
1.30.1 构造方法
- FileWriter(File file)根据给定的 File 对象构造一个 FileWriter 对象。
- FileWriter(File file, boolean append)根据给定的 File 对象构造一个 FileWriter 对象。
- FileWriter(FileDescriptor fd)构造与某个文件描述符相关联的 FileWriter 对象。
- FileWriter(String fileName)根据给定的文件名构造一个 FileWriter 对象。
- FileWriter(String fileName, boolean append)根据给定的文件名以及指示是否附加写入数据的 boolean 值来构造 FileWriter 对象。
1.30.2 成员方法
- void close()关闭此流,但要先刷新它。
- void flush()刷新该流的缓冲。
- void newLine()写入一个行分隔符。
- void write(char[] cbuf, int off, int len)写入字符数组的某一部分。
- void write(int c)写入单个字符。
- void write(String s, int off, int len)写入字符串的某一部分。
1.30.3 Demo
package com.xzy.JavaAPI.java.io.FileWriter;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
public class FileWriterP {
public static void main(String[] args) {
}
private static void part2() {
ArrayList<StringBuffer> sb = new ArrayList<>();
BufferedReader br=null;
try {
br=new BufferedReader(new FileReader("a.txt"));
String st=null;
while ((st = br.readLine()) != null) {
sb.add(new StringBuffer(st));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("大转盘");
for (int i = 0; i < 10; i++) {
int x = new Random().nextInt(sb.size());
System.out.println(sb.get(x));
}
}
private static void part1() {
ArrayList<StringBuffer> sb = new ArrayList<>();
for (int i = 0; i < 100; i++) {
sb.add(new StringBuffer(String.valueOf(i)));
}
BufferedWriter bw=null;
try {
bw=new BufferedWriter(new FileWriter("a.txt"));
for (StringBuffer sbc : sb) {
bw.write(new String(sbc));
if (Integer.valueOf(new String(sbc))<(sb.size()-1)) {
bw.flush();
bw.newLine();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1.31 java.io.LineNumberReader
1.31.1 构造方法
- LineNumberReader(Reader in)使用默认输入缓冲区的大小创建新的行编号 reader。
- LineNumberReader(Reader in, int sz)创建新的行编号 reader,将字符读入给定大小的缓冲区。
1.31.2 成员方法
- int getLineNumber()获得当前行号。
- void mark(int readAheadLimit)标记该流中的当前位置。
- int read()读取单个字符。
- int read(char[] cbuf, int off, int len)将字符读入数组中的某一部分。
- String readLine()读取文本行。
- void reset()将该流重新设置为最新的标记。
- void setLineNumber(int lineNumber)设置当前行号。
- long skip(long n)跳过字符。
1.31.3 Demo
package com.xzy.JavaAPI.java.io.LineNumberReader;
import java.io.*;
/**
* @Path com.xzy.JavaAPI.java.io.LineNumberReader.LineNumberReaderP
* @Description
* @Author xuzhiyong
* @DateTime 2020/5/31 1:26
* @Version 1.0
* 1.FIXME{@link Void}{@link LineNumberReaderP#getLineNumberP1()}1.0练习getLineNumber方法
*/
public class LineNumberReaderP {
public static void main(String[] args) {
}
/**
* @Method {@link LineNumberReaderP#getLineNumberP1()}
* @Return {@link Void}
* @Description 练习getLineNumber方法
* @Version 1.0
*/
public static void getLineNumberP1() {
BufferedReader br=null;
LineNumberReader lnr=null;
BufferedWriter bw=null;
File f = new File("a\\a-1-test.txt");
try {
br = new BufferedReader(new FileReader(f));
/*//写入测试数据
bw=new BufferedWriter(new FileWriter(f));
for (int i = 0; i < 20; i++) {
bw.write(String.valueOf(i));
bw.newLine();
}
bw.flush();*/
lnr = new LineNumberReader(new FileReader(f));
String str=null;
//获取行号new LineNumberReader.getLineNumber
while ((str = lnr.readLine()) != null) {
System.out.println(lnr.getLineNumber()+":"+str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
lnr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1.32 java.io.DataInputStream
1.32.1 构造方法
- DataInputStream(InputStream in)使用指定的底层 InputStream 创建一个 DataInputStream。
1.32.2 成员方法
- byte readByte()参见 DataInput 的 readByte 方法的常规协定。
1.32.3 Demo
package com.xzy.JavaAPI.java.io.DataInputStream;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import java.io.*;
/**
* @Path com.xzy.JavaAPI.java.io.DataInputStream.DataInputStreamP
* @Description DataInputStream应用在网络编程中
* @Author xuzhiyong
* @DateTime 2020/5/31 2:25
* @Version 1.0
*/
public class DataInputStreamP {
//日志记录
private static Logger logger=LoggerFactory.getLogger(DataInputStreamP.class);
public static void main(String[] args) {
DataInputStream dps=null;
try {
FileInputStream fis = new FileInputStream("a\\a-2-test1.txt");
dps = new DataInputStream(fis);
//写和读顺序一致性
int read = dps.read();
byte b = dps.readByte();
System.out.println(read+","+b);
} catch (FileNotFoundException e) {
logger.warn("FileNotFoundException",e);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dps != null) {
try {
dps.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
1.33 java.io.DataOutputStream
1.33.1 构造方法
- DataOutputStream(OutputStream out)创建一个新的数据输出流,将数据写入指定基础输出流。
1.33.2 成员方法
- void writeByte(int v)将一个 byte 值以 1-byte 值形式写出到基础输出流中。
1.33.3 Demo
package com.xzy.JavaAPI.java.io.DataOutputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @Path com.xzy.JavaAPI.java.io.DataOutputStream.DataOutputStreamP
* @Description DataOutputStream应用在网络编程中
* @Author xuzhiyong
* @DateTime 2020/5/31 2:26
* @Version 1.0
*/
public class DataOutputStreamP {
public static void main(String[] args) {
//引用赋空
DataOutputStream dps=null;
//创建数据输出流对象
try {
FileOutputStream fps = new FileOutputStream("a\\a-2-test.txt");
dps=new DataOutputStream(fps);
//可以写入8中基本数据类型和包装类型,写和读顺序一致性
dps.write(100);
dps.writeByte(20);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
dps.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1.34 java.io.ByteArrayOutputStream
1.34.1 构造方法
- ByteArrayOutputStream()创建一个新的 byte 数组输出流。
- ByteArrayOutputStream(int size)创建一个新的 byte 数组输出流,它具有指定大小的缓冲区容量(以字节为单位)。
1.34.2 成员方法
- void close()关闭 ByteArrayOutputStream 无效。
- void reset()将此 byte 数组输出流的 count 字段重置为零,从而丢弃输出流中目前已累积的所有输出。
- int size()返回缓冲区的当前大小。
- byte[] toByteArray()创建一个新分配的 byte 数组。
- String toString()使用平台默认的字符集,通过解码字节将缓冲区内容转换为字符串。
- String toString(int hibyte)已过时。 此方法无法将字节正确转换为字符。从 JDK 1.1 开始,完成该转换的首选方法是通过 toString(String enc) 方法(使用一个编码名称参数),或 toString() 方法(使用平台的默认字符编码)。
- String toString(String charsetName)用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串。
- void write(byte[] b, int off, int len)将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此 byte 数组输出流。
- void write(int b)将指定的字节写入此 byte 数组输出流。
- void writeTo(OutputStream out)将此 byte 数组输出流的全部内容写入到指定的输出流参数中,这与使用 out.write(buf, 0, count) 调用该输出流的 write 方法效果一样。
1.34.3 Demo
package com.xzy.JavaAPI.java.io.ByteArrayOutputStream;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ByteArrayOutputStreamP {
//日志记录
private static Logger logger = LoggerFactory.getLogger(ByteArrayOutputStreamP.class);
public static void main(String[] args) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
baos.write("hello".getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/*byte[] bytes = baos.toByteArray();
System.out.println(new String(bytes));*/
}
}
1.35 java.io.ByteArrayInputStream
1.35.1 构造方法
- ByteArrayInputStream(byte[] buf)创建一个 ByteArrayInputStream,使用 buf 作为其缓冲区数组。
- ByteArrayInputStream(byte[] buf, int offset, int length)创建 ByteArrayInputStream,使用 buf 作为其缓冲区数组。
1.35.2 成员方法
- int available()返回可从此输入流读取(或跳过)的剩余字节数。
- void close()关闭 ByteArrayInputStream 无效。
- void mark(int readAheadLimit)设置流中的当前标记位置。
- boolean markSupported()测试此 InputStream 是否支持 mark/reset。
- int read()从此输入流中读取下一个数据字节。
- int read(byte[] b, int off, int len)将最多 len 个数据字节从此输入流读入 byte 数组。
- void reset()将缓冲区的位置重置为标记位置。
- long skip(long n)从此输入流中跳过 n 个输入字节。
1.36 java.io.CharArrayReader
1.36.1 构造方法
- CharArrayReader(char[] buf)根据指定的 char 数组创建一个 CharArrayReader。
- CharArrayReader(char[] buf, int offset, int length)根据指定的 char 数组创建一个 CharArrayReader。
1.36.2 成员方法
- void close()关闭该流并释放与之关联的所有系统资源。
- void mark(int readAheadLimit)标记流中的当前位置。
- boolean markSupported()判断此流是否支持 mark() 操作(它一定支持)。
- int read()读取单个字符。
- int read(char[] b, int off, int len)将字符读入数组的某一部分。
- boolean ready()判断此流是否已准备好被读取。
- void reset()将该流重置为最新的标记,如果从未标记过,则将其重置到开头。
- long skip(long n)跳过字符。
1.37 java.io.CharArrayWriter
1.37.1 构造方法
- CharArrayWriter()创建一个新的 CharArrayWriter。
- CharArrayWriter(int initialSize)创建一个具有指定初始大小的新 CharArrayWriter。
1.37.2 成员方法
- CharArrayWriter append(char c)将指定字符添加到此 writer。
- CharArrayWriter append(CharSequence csq)将指定的字符序列添加到此 writer。
- CharArrayWriter append(CharSequence csq, int start, int end)将指定字符序列的子序列添加到此 writer。
- void close()关闭该流。
- void flush()刷新该流的缓冲。
- void reset()重置该缓冲区,以便再次使用它而无需丢弃已分配的缓冲区。
- int size()返回缓冲区的当前大小。
- char[] toCharArray()返回输入数据的副本。
- String toString()将输入数据转换为字符串。
- void write(char[] c, int off, int len)将字符写入缓冲区。
- void write(int c)将一个字符写入缓冲区。
- void write(String str, int off, int len)将字符串的某一部分写入缓冲区。
- void writeTo(Writer out)将缓冲区的内容写入另一个字符流。
1.37.3 Demo
package com.xzy.JavaAPI.java.io.CharArrayWriter;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.IOException;
/**
* @Path com.xzy.JavaAPI.java.io.CharArrayWriter.CharArrayWriterP
* @Description
* @Author xuzhiyong
* @DateTime 2020/5/31 23:09
* @Version 1.0
*/
public class CharArrayWriterP {
public static void main(String[] args) throws IOException {
CharArrayWriter caw = new CharArrayWriter();
char[] arr={'h','e'};
try {
caw.write(arr);
} catch (IOException e) {
e.printStackTrace();
}finally {
caw.close();
}
// char[] data = caw.toCharArray();
String data = caw.toString();
System.out.println(data);
CharArrayReader car = new CharArrayReader(data.toCharArray());
// int len;
// while ((len = car.read()) != -1) {
// System.out.println((char) len);
// }
System.out.println(car);
}
}
1.38 java.io.PrintWriter
1.38.1 构造方法
- PrintWriter(File file)使用指定文件创建不具有自动行刷新的新 PrintWriter。
- PrintWriter(File file, String csn)创建具有指定文件和字符集且不带自动刷行新的新 PrintWriter。
- PrintWriter(OutputStream out)根据现有的 OutputStream 创建不带自动行刷新的新 PrintWriter。
- PrintWriter(OutputStream out, boolean autoFlush)通过现有的 OutputStream 创建新的 PrintWriter。
- PrintWriter(String fileName)创建具有指定文件名称且不带自动行刷新的新 PrintWriter。
- PrintWriter(String fileName, String csn)创建具有指定文件名称和字符集且不带自动行刷新的新 PrintWriter。
- PrintWriter(Writer out)创建不带自动行刷新的新 PrintWriter。
- PrintWriter(Writer out, boolean autoFlush)创建新 PrintWriter。
1.38.2 成员方法
- void write(String s)写入字符串。
1.38.3 Demo
package com.xzy.JavaAPI.java.io.PrintWriter;
import java.io.*;
public class PrintWriterP {
public static void main(String[] args) throws FileNotFoundException {
PrintWriter pr = null;
try {
// pr = new PrintWriter("b.txt");
//第一种构造方法
// pr=new PrintWriter(new FileWriter("b.txt"),true);//开启自动刷新
//第二种构造方法
pr = new PrintWriter(new FileOutputStream("b.txt"), true);//开启自动刷新
/*{
注意!JDK8u231自动PrintWriter刷新开启,但是程序仍然未刷新
}*/
pr.print("good");
pr.print("good");
pr.print("good");
pr.print("good");
System.out.println("----");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// pr.flush();//刷新或者关闭都会刷新
// if (pr != null) {
// pr.close();
}
}
}
1.39 java.io.PrintStream
1.39.1 构造方法
- PrintStream(OutputStream out)创建新的打印流。
1.39.2 成员方法
- void write(byte[] buf, int off, int len)将 len 字节从指定的初始偏移量为 off 的 byte 数组写入此流。
1.39.3 Demo
package com.xzy.JavaAPI.java.io.PrintStream;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import java.io.*;
/**
* @Class PrintStreamP
* @Description
* @Author xuzhiyong
* @DateTime 2020/6/1 17:16
* @Version 1.0
*/
public class PrintStreamP {
//日志记录
private static Logger logger = LoggerFactory.getLogger(PrintStreamP.class);
public static void main(String[] args) {
FileOutputStream fos = null;
FileInputStream fis=null;
try {
fos = new FileOutputStream("E:\\github\\JavaCodebase\\b\\b-10-test.txt");
fis = new FileInputStream("E:\\github\\JavaCodebase\\b\\b-9-test.txt");
PrintStream ps = new PrintStream(fos);
byte[] bys = new byte[1024];
int len;
while ((len = fis.read(bys)) != -1) {
ps.write(bys,0,len);//字节写入和读取保持一致
}
ps.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();
}
}
}
}
}
1.40 java.io.RandomAccessFile
1.40.1 构造方法
- RandomAccessFile(File file, String mode)创建从中读取和向其中写入(可选)的随机访问文件流,该文件由 File 参数指定。
- RandomAccessFile(String name, String mode)创建从中读取和向其中写入(可选)的随机访问文件流,该文件具有指定名称。
1.40.2 成员方法
- int readInt()从此文件读取一个有符号的 32 位整数。
- void writeInt(int v)按四个字节将 int 写入该文件,先写高字节。
- FileDescriptor getFD()返回与此流关联的不透明文件描述符对象。
- long getFilePointer()返回此文件中的当前偏移量。
1.40.3 Demo
package com.xzy.JavaAPI.java.io.RandomAccessFile;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* @Class RandomAccessFileP
* @Description
* @Author xuzhiyong
* @DateTime 2020/6/1 21:28
* @Version 1.0
*/
public class RandomAccessFileP {
//日志记录
private static Logger logger = LoggerFactory.getLogger(RandomAccessFileP.class);
public static void main(String[] args) {
}
public static void readAndWriteMethod1() {
String name = new String("E:\\github\\JavaCodebase\\b\\b-1-test.txt");
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(name, "rw");
// raf.writeInt(100);//读写一致
System.out.println(raf.readInt());//读写一致
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
1.41 java.io.SequenceInputStream
1.41.1 构造方法
- SequenceInputStream(Enumeration<? extends InputStream> e)通过记住参数来初始化新创建的 SequenceInputStream,该参数必须是生成运行时类型为 InputStream 对象的 Enumeration 型参数。
- SequenceInputStream(InputStream s1, InputStream s2)通过记住这两个参数来初始化新创建的 SequenceInputStream(将按顺序读取这两个参数,先读取 s1,然后读取 s2),以提供从此 SequenceInputStream 读取的字节。
1.41.2 成员方法
- int available()返回不受阻塞地从当前底层输入流读取(或跳过)的字节数的估计值,方法是通过下一次调用当前底层输入流的方法。
- void close()关闭此输入流并释放与此流关联的所有系统资源。
- int read()从此输入流中读取下一个数据字节。
- int read(byte[] b, int off, int len)将最多 len 个数据字节从此输入流读入 byte 数组。
1.41.3 Demo
package com.xzy.JavaAPI.java.io.SequenceInputStream;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import java.io.*;
import java.util.Enumeration;
import java.util.Vector;
/**
* @Class SequenceInputStreamP
* @Description
* @Author xuzhiyong
* @DateTime 2020/6/1 23:23
* @Version 1.0
*/
public class SequenceInputStreamP {
//日志记录
private static Logger logger = LoggerFactory.getLogger(SequenceInputStreamP.class);
public static void main(String[] args) {
}
public static void constructionMethod2() {
String in1 = new String("E:\\github\\JavaCodebase\\b\\b-2-test.txt");
String in2 = new String("E:\\github\\JavaCodebase\\b\\b-3-test.txt");
String in3 = new String("E:\\github\\JavaCodebase\\b\\b-5-test.txt");
FileInputStream fis1 =null;
FileInputStream fis2 =null;
FileInputStream fis3 =null;
Vector<InputStream> is = new Vector<>();
try {
fis1 = new FileInputStream(in1);
fis2 = new FileInputStream(in2);
fis3 = new FileInputStream(in3);
is.add(fis1);
is.add(fis2);
is.add(fis3);
Enumeration<InputStream> ele = is.elements();
FileOutputStream fos = new FileOutputStream("E:\\github\\JavaCodebase\\b\\b-4-test.txt");
SequenceInputStream sis = new SequenceInputStream(ele);
/*byte[] bys = new byte[1024];
int len;
while ((len = sis.read(bys)) != -1) {
fos.write(bys,0,len);
}*/
int len;
while ((len = sis.read()) != -1) {
fos.write(len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis1 != null) {
try {
fis1.close();
fis2.close();
fis3.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void constructionMethod1() {
String in1 = new String("E:\\github\\JavaCodebase\\b\\b-2-test.txt");
String in2 = new String("E:\\github\\JavaCodebase\\b\\b-3-test.txt");
FileInputStream fis1 =null;
FileInputStream fis2 =null;
try {
fis1 = new FileInputStream(in1);
fis2 = new FileInputStream(in2);
FileOutputStream fos = new FileOutputStream("E:\\github\\JavaCodebase\\b\\b-4-test.txt");
SequenceInputStream sis = new SequenceInputStream(fis1,fis2);
/*byte[] bys = new byte[1024];
int len;
while ((len = sis.read(bys)) != -1) {
fos.write(bys,0,len);
}*/
int len;
while ((len = sis.read()) != -1) {
fos.write(len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis1 != null) {
try {
fis1.close();
fis2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
1.42 java.io.ObjectOutputStream
1.42.1 构造方法
- protected ObjectOutputStream()为完全重新实现 ObjectOutputStream 的子类提供一种方法,让它不必分配仅由 ObjectOutputStream 的实现使用的私有数据。
- ObjectOutputStream(OutputStream out)创建写入指定 OutputStream 的 ObjectOutputStream。
1.42.2 成员方法
- void writeObject(Object obj)将指定的对象写入 ObjectOutputStream。
1.42.3 Demo
package com.xzy.JavaAPI.java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* @Class Student
* @Description 序列化版本ID
* 序列化非持久关键字transient,不允许序列化到硬盘上
* @Author xuzhiyong
* @DateTime 2020/6/2 3:14
* @Version 1.0
*/
public class Student implements Serializable {
private static final long serialVersionUID = -5005869420439727374L;//序列化版本ID
private transient String name;//序列化非持久关键字transient,不允许序列化到硬盘上
private Integer age;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public Student() {
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
package com.xzy.JavaAPI.java.io.ObjectOutputStream;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import java.io.*;
/**
* @Class ObjectOutputStreamP
* @Description 序列化和反序列化,序列化对象需要实现Serializable接口,反序列化的包名和序列化时应一致。
*
* @Author xuzhiyong
* @DateTime 2020/6/2 2:39
* @Version 1.0
*/
public class ObjectOutputStreamP {
//日志记录
private static Logger logger = LoggerFactory.getLogger(ObjectOutputStreamP.class);
public static void main(String[] args) {
}
public static void constructionMethodAndreadObjectMethod2() {
FileInputStream fis =null;
ObjectInputStream ois =null;
try {
fis = new FileInputStream("Student.txt");
ois = new ObjectInputStream(fis);
Student stu = (Student) ois.readObject();
System.out.println(stu.getName() + stu.getAge());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void constructionMethodAndWriteObjectMethod1() {
Student stu1 = new Student("xzy", 20);
FileOutputStream fs =null;
try {
fs = new FileOutputStream("Student.txt");
ObjectOutputStream oos = new ObjectOutputStream(fs);
oos.writeObject(stu1);
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fs != null) {
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
1.43 java.io.ObjectInputStream
1.43.1 构造方法
- protected ObjectInputStream()为完全重新实现 ObjectInputStream 的子类提供一种方式,让它不必分配仅由 ObjectInputStream 的实现使用的私有数据。
- ObjectInputStream(InputStream in)创建从指定 InputStream 读取的 ObjectInputStream。
1.43.2 成员方法
- Object readObject()从 ObjectInputStream 读取对象。
1.44 java.util.Properties
1.44.1 构造方法
- Properties()创建一个无默认值的空属性列表。
- Properties(Properties defaults)创建一个带有指定默认值的空属性列表。
1.44.2 成员方法
- Set keySet()获得key集合
- Set<Map.entry<Object,Object>> entrySet()获得key+value
- Enumeration elements获得value集合
- Object put(Object,Object)添加数据
- Object setProperty(String,String)
- Set stringPropertyNames返回key,前提是使用setProperty添加数据
- String getProperty(String)返回value
- void store(FileWriter,String)将数据写入到FileWriter指向的文件
- void load(FileReader)将指向文件中数据加载进集合
1.44.3 Demo
package com.xzy.JavaAPI.java.util.Properties;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import jdk.nashorn.internal.parser.JSONParser;
import jdk.nashorn.internal.runtime.JSONFunctions;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
* @Class PropertiesP
* @Description
* @Author xuzhiyong
* @DateTime 2020/6/2 3:40
* @Version 1.0
*/
public class PropertiesP {
//日志记录
private static Logger logger = LoggerFactory.getLogger(PropertiesP.class);
public static void main(String[] args) {
}
public static void method3() {
Properties pr = new Properties();
String str = new String("E:\\github\\JavaCodebase\\b\\b-2-test.txt");
System.out.println("------------------------------------");
FileReader fr=null;
try {
fr=new FileReader(str);
pr.load(fr);
Set<Object> keys = pr.keySet();//不太完美,是否可以使用本地工具类转换成Set<String>
for (Object key : keys) {
String value = (String) pr.get(key);
System.out.println(key + "::" + value);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void method2() {
Properties pr = new Properties();
pr.put("xzy","101");//pr.put("xzy",101)运行报错,为何?
pr.put("Tom","102");
pr.put("Tom","103");
String str = new String("E:\\github\\JavaCodebase\\b\\b-2-test.txt");
FileWriter fw =null;
try {
fw = new FileWriter(str);
pr.store(fw,"hello");
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void method1() {
Properties pr = new Properties();
pr.put("xzy","20");
System.out.println(pr);
//遍历key
Set<Object> ob = pr.keySet();
for (Object key : ob) {
Object value = pr.get(key);
System.out.println(key + ":" + value);
}
//遍历key+value
Set<Map.Entry<Object, Object>> en = pr.entrySet();
for (Map.Entry<Object, Object> ent : en) {
System.out.println(ent.getKey() + ":" + ent.getValue());
}
//遍历所有的value
Enumeration<Object> el = pr.elements();
while (el.hasMoreElements()) {
Object value = el.nextElement();
System.out.println(value);
}
System.out.println("-------------------------------------");
pr.setProperty("yy","100");//参数先定位String
//获得key集合
Set<String> keys = pr.stringPropertyNames();
System.out.println(keys);
for (String key : keys) {
String value = pr.getProperty(key);
System.out.println(key + "::" + value);
}
}
}