一、集合框架
1.1、为什么使用集合框架
在编程时,可以使用数组来保存多个对象,但数组长度不可变化,一旦在初始化数组时指定了数组长度,这个数组长度就是不可变的。如果需要保存数量变化的数据,数组就有点无能为力了。而且数组无法保存具有映射关系的数据,如成绩表为语文——79,数学——80,这种数据看上去像两个数组,但这两个数组的元素之间有一定的关联关系。
为了保存数量不确定的数据,以及保存具有映射关系的数据(也被称为关联数组),Java 提供了集合类。
1.2、集合
-集合类主要负责保存、盛装其他数据,因此集合类也被称为容器类。Java 所有的集合类都位于 java.util 包下,提供了一个表示和操作对象集合的统一构架,包含大量集合接口,以及这些接口的实现类和操作它们的算法。
1.2.1、 collection接口
collection接口储存一组不唯一,无序的对像;
1.2.2、 List接口
List 接口存储一组不唯一,有序(插入顺序)的对象
(1)ArrayList实现了长度可变的数组,在内存中分配连续的空间,遍历元素和随机访问元素的效率比较高.
ArrayList常用方法
Collection接口常用通用方法还有:clear()、isEmpty()、iterator()、toArray()
常用方法实例
public class Test {
public static void main(String[] args) {
//创建三个新闻对象
NewsTitle nt1 = new NewsTitle(1001, "新闻1", "合肥日报");
NewsTitle nt2 = new NewsTitle(1002, "新闻2", "合肥月报");
NewsTitle nt3 = new NewsTitle(1003, "新闻3", "合肥年报");
NewsTitle nt4 = new NewsTitle(1004, "新闻4", "合肥年报");
//准备集合容器,调用ArrayList类的无参构造方法
ArrayList al = new ArrayList();
//将创建的新闻对象存储到al集合中
al.add(nt1);//add()返回boolean类型
al.add(nt2);//add()返回boolean类型
al.add(nt3);//add()返回boolean类型
//获取集合个数
int num = al.size();
System.out.println(num);
System.out.println("------------------------------");
//打印每条新闻的名称
for (int i = 0; i <al.size(); i++) {
//Object obj = al.get(i);
NewsTitle nt = (NewsTitle)al.get(i);
System.out.println(nt.getName());
}
System.out.println("------------------------------");
//void add(int index,Object o)在指定的索引位置添加元素。索引位置必须介于0和列表中元素个数之间
al.add(0,nt4);
NewsTitle nt = (NewsTitle)al.get(0);
System.out.println(nt);
System.out.println("------------------------------");
//boolean contains(Object o):判断列表中是否存在指定元素,如果集合中存在你要找的元素,返回true,否则返回false
boolean result1 = al.contains(nt4);
System.out.println("是否存在" + result1);
System.out.println("------------------------------");
//boolean remove(Object o):从列表中删除元素,删除成功返回true,删除失败返回false
boolean result2 = al.remove(nt3);
System.out.println("删除成功" + result2);
for (int i = 0; i <al.size(); i++) {
//Object obj = al.get(i);
NewsTitle nt31 = (NewsTitle)al.get(i);
System.out.println(nt31.getName());
}
System.out.println("------------------------------");
//Object remove(int index):从列表中删除指定位置元素,起始索引位置从0开始
Object obj =al.remove(0);
NewsTitle newsTile = (NewsTitle) obj;
System.out.println(newsTile);
System.out.println("------------------------------");
for (int i = 0; i < al.size(); i++) {
Object obje = al.get(i);
NewsTitle newsTilee = (NewsTitle) obje;
System.out.println(newsTilee.getId()+"--"+newsTilee.getName());
}
System.out.println("------------------------------");
//clear():清空集合中的所有元素
al.clear();
System.out.println(al.size());
}
}
ArrayList集合实例
新闻管理系统,需求如下
- 可以存储各类新闻标题(包含ID、名称、创建者)
- 可以获取新闻标题的总数
- 可以逐条打印每条新闻标题的名称
NewsTitle.java
public class NewsTitle {
private int id;
private String name;
private String author;
public NewsTitle() {
super();
}
public NewsTitle(int id, String name, String author) {
super();
this.id = id;
this.name = name;
this.author = author;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
Test.java
public class Test {
public static void main(String[] args) {
//创建三个新闻对象
NewsTitle nt1 = new NewsTitle(1001, "新闻1", "合肥日报");
NewsTitle nt2 = new NewsTitle(1002, "新闻2", "合肥月报");
NewsTitle nt3 = new NewsTitle(1003, "新闻3", "合肥年报");
//准备集合容器,调用ArrayList类的无参构造方法
ArrayList al = new ArrayList();
//将创建的新闻对象存储到al集合中
al.add(nt1);//add()返回boolean类型
al.add(nt2);//add()返回boolean类型
al.add(nt3);//add()返回boolean类型
//获取集合个数
int num = al.size();
System.out.println(num);
//打印每条新闻的名称
for (int i = 0; i <al.size(); i++) {
//Object obj = al.get(i);
NewsTitle nt = (NewsTitle)al.get(i);
System.out.println(nt.getName());
}
}
}
(2)LinkedList采用链表存储方式,插入、删除元素时效率比较高
LinkedList常用方法
LinkedList集合实例
新闻管理系统,需求如下
- 可以添加头条新闻标题
- 获取头条和最末条新闻标题
- 可以删除末条新闻标题
NewsTitle.java(和ArrayList一样)
Test.java
public class Test {
public static void main(String[] args) {
//创建三个新闻对象
NewsTitle nt1 = new NewsTitle(1001, "新闻1", "合肥日报");
NewsTitle nt2 = new NewsTitle(1002, "新闻2", "合肥月报");
NewsTitle nt3 = new NewsTitle(1003, "新闻3", "合肥年报");
NewsTitle nt4 = new NewsTitle(1004, "新闻4", "合肥年年报");
//准备集合容器,调用List类的无参构造方法
LinkedList list = new LinkedList();
list.add(nt1);
list.add(nt2);
list.add(nt3);
list.addFirst(nt4);
for (Object object : list) {
System.out.println(object);
}
System.out.println("----------------------------------------");
//获取元素
System.out.println(list.getFirst());
System.out.println(list.getLast());
System.out.println("----------------------------------------");
//删除元素
list.removeFirst();
list.removeLast();
for (Object object : list) {
System.out.println(object);
}
}
}
1.2.3、 Set接口
- Set 接口存储一组唯一,无序的对象
- HashSet是Set接口常用的实现类
- Set中存放对象的引用
public class Demo01 {
public static void main(String[] args) {
Set set = new HashSet();
String s1 = new String("java");
String s2 = s1;
String s3 = new String("JAVA");
set.add(s1);
set.add(s2);
set.add(s3);
set.add(s3);
System.out.println(set.size());
for (Object object : set) {
System.out.println(object);
}
}
}
1.HashSet是Set接口常用的实现类
2. 遍历Set集合
- 方法1:通过迭代器Iterator实现遍历
- 获取Iterator :Collection 接口的iterator()方法
- Iterator的方法
- boolean hasNext(): 判断是否存在另一个可访问的元素
- Object next():返回要访问的下一个元素
- 方法2:增强型for循环
代码实例
public class Test {
public static void main(String[] args) {
//创建新闻对象
NewsTitle nt1 = new NewsTitle(1001, "新闻1", "合肥日报");
NewsTitle nt2 = new NewsTitle(1002, "新闻2", "合肥月报");
NewsTitle nt3 = new NewsTitle(1003, "新闻3", "合肥年报");
NewsTitle nt4 = new NewsTitle(1004, "新闻4", "合肥年年报");
//准备集合容器,调用hash类的无参构造方法
HashSet hs = new HashSet();
hs.add(nt1);
hs.add(nt2);
hs.add(nt3);
hs.add(nt4);
System.out.println(hs.size());
//增强型for循环
for (Object object : hs) {
System.out.println(object);
}
//通过迭代器Iterator实现遍历
System.out.println("------------------------------------------------");
Iterator it = hs.iterator();
while (it.hasNext()) {
Object object = it.next();
NewsTitle nt = (NewsTitle)object;
System.out.println(nt);
}
}
}
1.2.4 、Map接口
- Map接口存储一组键值对象,提供key到value的映射
最常用的实现类是HashMap。 - Map接口常用方法
- 遍历Map集合
方法1:通过迭代器Iterator实现遍历
方法2:增强型for循环
方法3:键值对
public class Test {
public static void main(String[] args) {
//准备键值对容器用来存储键值对
HashMap hm = new HashMap();
//向集合中存储数据
hm.put("CN", "中华人民共和国");
hm.put("RU","俄罗斯联邦");
hm.put("US", "美利坚合众国");
hm.put("JP", "日本");
System.out.println(hm.size());//4
Object obj1 =hm.get("CN");
String str1 = (String)obj1;
System.out.println(str1);
//Object remove(key):根据键来删除键值对,返回值是键对应的值
Object obj2 =hm.remove("JP");
String str2 = (String)obj2;
System.out.println(str2);
System.out.println(hm.size());//3
System.out.println(hm.containsKey("CN"));//true
System.out.println(hm.containsKey("JP"));//false
System.out.println(hm.containsValue("中华人民共和国"));//true
//keySet():返回集合中所有键值对的键的集合
Set keys=hm.keySet();
for (Object object : keys) {
String key = (String)object;
Object obj =hm.get(key);
String value = (String)obj;
System.out.println(key+"---"+value);
}
System.out.println("--------------------");
//Collection values():获取值得集合
Collection coll = hm.values();
for (Object object : coll) {
String value = (String)object;
System.out.println(value);
}
System.out.println("--------------------");
//获取键的集合
Set keys2 = hm.keySet();
Iterator it = keys2.iterator();
while(it.hasNext()){
Object obj =it.next();
String key = (String)obj;
Object obje=hm.get(key);
String value = (String)obje;
System.out.println(key+"---"+value);
}
System.out.println("--------------------");
//使用键值对的方式取出集合中的键值对
Set keyValues = hm.entrySet(); //将集合中的键值对全部取出来存储到Set集合
Iterator iterator =keyValues.iterator();//将Set集合中的元素存储到迭代器中
while(iterator.hasNext()){
Object obj =iterator.next();//使用next()方法获取迭代器中的元素
Map.Entry me = (Map.Entry)obj;//键值对元素的类型为Map.Entry
Object obje1 = me.getKey();//键值对类型对象调用getKey()方法可以获取键值对的键
String key =(String)obje1;
Object obje2 =me.getValue();//键值对类型对象调用getValue()方法可以获取键值对的值
String value =(String)obje2;
System.out.println(key+"~~~~~"+value);
}
}
}
二、泛型
如何解决以下强制类型转换时容易出现的异常问题
- List的get(int index)方法获取元素
- Map的get(Object key)方法获取元素
- Iterator的next()方法获取元素
通过泛型 - JDK5.0使用泛型改写了集合框架中的所有接口和类
2.1、概念
将对象的类型作为参数,指定到其他类或者方法上,从而保证类型转换的安全性和稳定性
-
本质是参数化类型
-
泛型集合可以约束集合内的元素类型
-
典型泛型集合ArrayList、HashMap<K,V>
< E >、<K,V>表示该泛型集合中的元素类型
泛型集合中的数据不再转换为Object
未使用泛型集合和使用泛型集合对比
public class Test {
public static void main(String[] args) {
//准备键值对容器用来存储键值对
HashMap hm = new HashMap();
//向集合中存储数据
hm.put("CN", "中华人民共和国");
hm.put("RU","俄罗斯联邦");
hm.put("US", "美利坚合众国");
hm.put("JP", "日本");
//未使用泛型集合的代码
//使用键值对的方式取出集合中的键值对
Set keyValues = hm.entrySet(); //将集合中的键值对全部取出来存储到Set集合
Iterator iterator =keyValues.iterator();//将Set集合中的元素存储到迭代器中
while(iterator.hasNext()){
Object obj =iterator.next();//使用next()方法获取迭代器中的元素
Map.Entry me = (Map.Entry)obj;//键值对元素的类型为Map.Entry
Object obje1 = me.getKey();//键值对类型对象调用getKey()方法可以获取键值对的键
String key =(String)obje1;
Object obje2 =me.getValue();//键值对类型对象调用getValue()方法可以获取键值对的值
String value =(String)obje2;
System.out.println(key+"~~~~~"+value);
}
//使用泛型集合后的代码
//使用键值对的方式取出集合中的键值对
Set<Entry<String, String>> keyValues = hm.entrySet(); //将集合中的键值对全部取出来存储到Set集合
Iterator<Entry<String, String>> iterator =keyValues.iterator();//将Set集合中的元素存储到迭代器中
while(iterator.hasNext()){
Map.Entry<String, String> me = (Entry) iterator.next();
String key = me.getKey();
String value = me.getValue();;
System.out.println(key+"~~~~~"+value);
}
}
2.2、Collections算法类
- Java集合框架将针对不同数据结构算法的实现都保存在工具类中
- Collections类定义了一系列用于操作集合的静态方法
常用方法
Collections和Collection不同,前者是集合的操作类,后者是集合接口
Collections提供的常用静态方法 - sort():排序
- binarySearch():查找
- max()\min():查找最大\最小值
实现一个类的对象之间比较大小,该类要实现Comparable接口,重写compareTo()方法
代码实例
public class Demo01 {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("wseurfhu");
al.add("dsfsdf");
al.add("asdewre");
al.add("sdfsf");
al.add("afhth");
System.out.println("集合排序之前:");
for (String string : al) {
System.out.println(string);
}
//Collections.sort():对集合进行排序
Collections.sort(al);
System.out.println("集合排序后:");
for (String string : al) {
System.out.println(string);
}
//int binarySearch(集合名,查找的数据):查找元素,返回查找元素所在的下标,如果查找不到元素,返回一个负值。 注意:使用该方法之前,对先对集合进行升序排序,否则不能保证查询结果的正确性
int index = Collections.binarySearch(al, "sdfsfgj");
System.out.println(index);
//max()/min():求集合中的最大值最小值
String max = Collections.max(al);
System.out.println(max);
String min = Collections.min(al);
System.out.println(min);
Collections.reverse(al);
System.out.println("集合元素反转之后:");
Iterator<String> it=al.iterator();
while(it.hasNext()){
String str = it.next();
System.out.println(str);
}
}
}
三、实用类
3.1、枚举类
枚举类是由一组固定的常量组成的类型
Genders.java
public enum Genders {
//枚举是由一组固定常量组成的类型
男,女
}
Students.java
public class Student {
public String name;
public Genders gender;
}
StudentTest,java
public class StudentTest {
public static void main(String[] args) {
//使用无参构造方法创建对象
Student stu = new Student();
//给属性赋值
stu.name = "张三";
stu.gender = Genders.男;
System.out.println(stu.name+"--"+stu.gender);
}
}
3.2、包装类
包装类把基本类型数据转换为对象
- 每个基本类型在java.lang包中都有一个相应的包装类
包装类的作用
- 提供了一系列实用的方法
- 集合不允许存放基本数据类型数据,存放数字时,要用包装类型
3.2.1、包装类的构造方法
所有包装类都可将与之对应的基本数据类型作为参数,来构造它们的实例
public Type(type value)
如:Integer i=new Integer(1);
除Character类外,其他包装类可将一个字符串作为参数构造它们的实例
public Type(String value)
如:Integer i=new Integer("123");
public class Demo02 {
public static void main(String[] args) {
// 所有包装类都可将与之对应的基本数据类型作为参数,来构造它们的实例
// 除Character类外,其他包装类可将一个字符串作为参数构造它们的实例(对于Number类型的对象,字符串需要是“数字形式的字符串”,也不能传递一个null值)
byte byt = 10;
// byte1是一个对象,这个对象里存储了数据byt
Byte byte1 = new Byte(byt);
Byte byte2 = new Byte("123");
// Byte byte3 = new Byte("abc");//NumberFormatException
System.out.println(Byte.MAX_VALUE);
System.out.println(Byte.MIN_VALUE);
System.out.println(byte2);
short sho = 100;
Short short1 = new Short(sho);
Short short2 = new Short("1343");
int num = 1000;
Integer integer = new Integer(num);
Integer integer2 = new Integer("1122");
long lon = 10000L;
Long long1 = new Long(lon);
Long long2 = new Long("156");
float flo = 100.5F;
Float float1 = new Float(flo);
Float float2 = new Float("12.5");
double dou = 99.88;
Double double1 = new Double(dou);
Double double2 = new Double("12.55");
boolean bool = true;
Boolean boolean1 = new Boolean(bool);
//字符串里的内容为true(不区分大小写)的时候,对象里存储的是true,其它所有情况都为false
Boolean boolean2 = new Boolean("sdsa");
System.out.println(boolean2);
char cha = '好';
Character character1 = new Character(cha);
System.out.println(Short.MAX_VALUE);
System.out.println(Short.MIN_VALUE);
}
}
注意事项
Boolean类构造方法参数为String类型时,若该字符串内容为true(不考虑大小写),则该Boolean对象表示true,否则表示false
当Number包装类构造方法参数为String类型时,字符串不能为null,且该字符串必须可解析为相应的基本数据类型的数据,否则编译不通过,运行时会抛出NumberFormatException异常
3.2.2、包装类的常用方法
public class Demo03 {
public static void main(String[] args) {
// 包装类常用方法
// XXXValue():包装类转换成基本类型
Long lon1 = new Long(125L);
long num1 = lon1.longValue();
// toString():以字符串形式返回包装对象表示的基本类型数据(基本类型->字符串)
String sex = Character.toString('男');
String str = Boolean.toString(true);
Integer inte = new Integer(100);
String str2 = inte.toString();
// parseXXX():把字符串转换为相应的基本数据类型数据(Character除外,并且字符串里面的内容要能够转换为数字,否则会报异常)(字符串->基本类型)
byte num2 = Byte.parseByte("123");
System.out.println(num2);
boolean result = Boolean.parseBoolean("TruE");
System.out.println(result);
// valueOf():所有包装类都有如下方法(基本类型->包装类) public static Type valueOf(type value)
byte byte2 = 10;
Byte byte3 = Byte.valueOf(byte2);
Character cha = Character.valueOf('女');
// 除Character类外,其他包装类都有如下方法(字符串->包装类)public static Type valueOf(String s)
Byte byte4 = Byte.valueOf("123");
// Character.valueOf("a");
}
}
3.2.3、 装箱和拆箱
public class Demo04 {
public static void main(String[] args) {
// 装箱和拆箱
byte byte1 = 10;
Byte byte2 = new Byte(byte1);
Byte byte3 = Byte.valueOf(byte1);
// 装箱:直接将基本数据类型赋值给了包装类对象
Byte byte4 = byte1;
System.out.println(byte4);
Integer int1 = new Integer(20);
int int2 = int1.intValue();
// 拆箱:将包装类对象直接赋值给基本数据类型的变量
int int3 = int1;
System.out.println(int3);
// JDK1.5后,允许基本数据类型和包装类型进行混合数学运算
Integer num1 = new Integer(100);
int num2 = 1000;
int sum = num1 + num2;
System.out.println(sum);
Integer sum2 = num1 + num2;
System.out.println(sum2);
}
}
3.3、Math类
java.lang.Math类提供了常用的数学运算方法和两个静态常量E(自然对数的底数) 和PI(圆周率)
public class DemoMath {
public static void main(String[] args) {
//abs()返回绝对值
double abs = Math.abs(-3.5); //返回3.5
System.out.println(abs);
//max()/min()返回两个中较大/较小值
double max = Math.max(2.5, 90.5);//返回90.5
double min = Math.min(2.5, 90.5);//返回2.5
System.out.println(max);
System.out.println(min);
//random()返回一个随机数
int random = (int) (Math.random() * 10); //生成一个0-9之间的随机数
System.out.println(random);
}
}
3.4、Random类
java.util.Random类
public class Demo03 {
public static void main(String[] args) {
Random rand=new Random(); //创建一个Random对象
for(int i=0;i<20;i++){//随机生成20个随机整数,并显示
int num=rand.nextInt(10);//返回下一个伪随机数,整型的
System.out.println("第"+(i+1)+"个随机数是:"+num);
}
}
}
3.5、String类
使用String对象存储字符串
String s1 = "Hello World";
String s2 = new String();
String s3 = new String("Hello World"");
String类位于java.lang包中,具有 丰富的方法
计算字符串的长度、比较字符串、连接字符串、提取字符串
package cn.bdqn.demo03;
public class StringDemo {
public static void main(String[] args) {
String str = "abcdefgabcqwerabdkg";
// length():获取字符串的长度
System.out.println(str.length());
String pwd = "aidsjfksj";
if (pwd.length() < 6 || pwd.length() > 18) {
System.out.println("密码长度应该在6-18之间,请重新输入");
}
System.out.println("------------------");
// equals():比较两个字符串的内容是否相同,英文字母区分大小写
String str1 = "abcdefg";
String str2 = "abcdefG";
System.out.println(str1.equals(str2));// false
// equalsIgnoreCase():比较两个字符串的内容是否相同,英文字母不区分大小写
System.out.println(str1.equalsIgnoreCase(str2));// true
// toLowerCase()方法:将大写英文字母转换为小写
// toUpperCase()方法:将小写英文字母转换为大写
String str3 = "ABCDqwer";
System.out.println(str3.toLowerCase());// abcdqwer
System.out.println(str3.toUpperCase());// ABCDQWER
}
}
注意:拼接符 + 的使用
public class Demo03 {
public static void main(String[] args) {
System.out.println(10+"hello"+20);//10hello20
//结果为hello1020 ,不是hello30,运算顺序为字符串"hello10"+20,hello1020
System.out.println("hello"+10+20);
//30hello,不是1020hello,运算顺序为字符串30+"hello",30hello
System.out.println(10+20+"hello");
}
}
使用String类的concat()方法
// 字符串的连接:+ concat()
String str4 = "你是";
String str5 = "一个好人";
System.out.println(str4+","+str5);
String result = str4.concat(str5);
System.out.println(result);
字符串常用提取方法
package cn.bdqn.demo03;
public class StringDemo02 {
public static void main(String[] args) {
// public int indexOf(int ch)搜索第一个出现的字符ch(或字符串value),如果没有找到,返回-1
// public int indexOf(String value)搜索第一个出现的字符ch(或字符串value),如果没有找到,返回-1
// 常用ASCII码值 A:65 a:97 0:48
String str = "abcdefghijk0lAmnabc";
int num = str.indexOf(48);
System.out.println(num);// 12
int index = str.indexOf("a");
System.out.println(index);// 0
// public int lastIndexOf(int ch):搜索最后一个出现的字符ch(或字符串value),如果没有找到,返回-1
// public int lastIndexOf(String
// value):搜索最后一个出现的字符ch(或字符串value),如果没有找到,返回-1
System.out.println(str.lastIndexOf("a"));
// public String substring(int index):提取从位置索引开始的字符串部分
String newStr = str.substring(3);
System.out.println(str);
System.out.println(newStr);
// public String substring(int beginindex, int
// endindex):提取beginindex和endindex之间的字符串部分,包括开始索引的字符,不包括结束索引的字符
String newStr2 = str.substring(3, 6);
System.out.println(str);
System.out.println(newStr2);
// public String trim():返回一个前后不含任何空格的调用字符串的副本
String str3 = " abc qwert ";
String newStr3 = str3.trim();
System.out.println(str3);
System.out.println(newStr3);
System.out.println("-----------------");
// String[] split(String regex) :根据拆分规则对字符串进行拆分
String song = "长亭外,古道边,芳草碧连天,晚风拂,柳笛声残,夕阳山外山";
String[] strs = song.split(",");
for (String string : strs) {
System.out.println(string);
}
// 我爱你你不爱我但是我很爱你可我就是不爱你
String love = "我爱你你不爱我但是我很爱你可我就是不爱你";
String[] loves = love.split("爱");
for (String string : loves) {
System.out.println(string);
}
System.out.println("--------------");
char ch = love.charAt(1);
System.out.println(ch);
boolean result = love.endsWith("爱你ya");
System.out.println(result);
byte[] bytes = love.getBytes();
System.out.println(bytes[0]);//-50
char result2 = (char) bytes[0];
System.out.println(result2);
// for (int i = 0; i < bytes.length; i++) {
// System.out.println(bytes[i]);
// }
}
}
三、输入和输出
2.1、文件File
2.1.1、文件
1、什么是文件:相关记录或放在一起的数据的集合
2、文件一般储存在硬盘、光盘、软盘等等设备中
3、Java程序是通过java.io,file类来访问文件属性
2.1.2、File类访问文件属性
File file = new File(String pathname); -------->>"C:\\test.txt"或者"C:/test.txt"
方法名称 | 说明 |
---|---|
boolean exists() | 判断文件或目录是否存在 |
boolean isFile() | 判断是否是文件 |
boolean isDirectory | 判断是否是目录 |
String getPath() | 返回此对象表示的文件的相对路径 |
String getAbsolutePath() | 返回此对象表示的文件的相对路径 |
String getName() | 返回此对象表示的文件或目录得到名称 |
boolean delete() | 删除此对象指定的文件或目录 |
boolean createNewFile() | 创建名称的空文件,不创建文件夹 |
long length() | 返回文件的长度,单位为字节,如果文件不存在,则返回0L |
代码示例
public class FileDemo01 {
public static void main(String[] args) {
// 创建file对象
File file = new File("D:\\demo.txt");
File file2 = new File("d:\\demo2.txt");
// 通过file调用方法实现对文件属性的操作
// exists()判断文件是否存在
boolean result1 = file.exists();
System.out.println(result1);
boolean result2 = file2.exists();
System.out.println(result2);
// boolean isFile():判断是否是文件
// isDirectory():判断是否是目录
boolean result3 = file.isFile();
System.out.println(result3);
// getPath()返回相对路径 ,file.getAbsolutePath()返回绝对路径
String pathname = file.getPath();
System.out.println(pathname);
System.out.println(file.getAbsolutePath());
// boolean createNewFile():创建名称的空文件,不创建文件夹
File file3 = new File("test.txt");
File file4 = new File("D:\\aa\\bb\\cc\\dd");
try {
boolean result5 = file3.createNewFile();
// mkdir() 创建此抽象路径名指定的目录
// mkdirs()创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。
boolean result6 = file4.mkdirs();
System.out.println("创建成功" + result6);
} catch (IOException e) {
e.printStackTrace();
}
//getName()
System.out.println(file3.getName());
//delete()
System.out.println("file3删除成功:" + file3.delete());
//length
System.out.println("file的长度为" + file.length());
}
}
2.2、流
2.2.1、通过流来读写文件
- 流是一组有序的数据序列
- 以先进先出的方式发送信息的通道
2.2.2、 输入/输出流与数据源
2.2.3、Java流的分类
1、按流向区分
- 输出流:OutputStream和Writer作为基类
- 输出流:InputStream和Reader作为基类
输入输出流是相对于计算机来说的
2、按照处理数据单元划分
- 字节流
字节输入流InputStream基类
字节输出流OutputStream基类 - 字符流
字符输入流Reader基类
字符输出流Writer基类
字节流是8位通用字节流,字符流是16位Unicode字符流
2.3、字节流
2.3.1、InputStream
InputStream类常用方法
- int read( )
- int read(byte[] b)
- int read(byte[] b,int off,int len)
- void close( )
- int available():可以从输入流中读取的字节数目
子类FileInputStream常用的构造方法
- FileInputStream(File file)
- FileInputStream(String name)
使用FileInputStream读文本文件
步骤:
- 引入相关的类
- 构造文件输入流FileInputStream对象
- 读取文本文件的数据
- 关闭文件流对象
代码示例1
public static void main(String[] args) throws IOException {
//创建File类对象
File file = new File("D:/demo.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
int num;
//调用方法读取内容
while ((num = fis.read()) != -1) {
char ch = (char)num;
System.out.print(ch);
}
System.out.println();
System.out.println("程序读取完毕");
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
fis.close();
}
}
代码示例2
public static void main(String[] args) {
File file = new File("D:\\Test.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
//通过fis对象调用方法将文件内容读取出来
//read()方法需要一个byte类型的参数,准备一个byte类型的参数
byte[] bytes = new byte[1024];
//int read(byte[] bytes) :从指定文件中读取数据,将读取的数据存储在一个byte类型的数组中,返回值表示从文件中读取的内容长度
int num = fis.read(bytes);
System.out.println(num);
for (int i = 0; i < bytes.length; i++) {
System.out.print((char)bytes[i]);
}
System.out.println("文件读取完毕");
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.3.2、OutputStream
OutputStream类常用方法
- void write(int c)
- void write(byte[] buf)
- void write(byte[] b,int off,int len)
- void close()
- void flush():强制把缓冲区的数据写到输出流中
子类FileOutputStream常用的构造方法
- FileOutputStream (File file)
- FileOutputStream(String name)
- FileOutputStream(String name,boolean append)
注意!
1.前两种构造方法在向文件写数据时将覆盖文件中原有的内容
2.创建FileOutputStream实例时,如果相应的文件并不存在,则会自动创建一个空的文件
使用FileOutputStream读文本文件
步骤:
- 引入相关的类
- 构造文件输入流FileOutputStream对象
- 将数据写如文本文件
- 关闭文件流对象
代码示例1
public static void main(String[] args) {
FileOutputStream os = null;
try {
// 创建一个OutputStream类对象指向FileOutputStream类对象
// FileOutputStream(String path):通过此构造方法创建的对象,使用write()方法写入数据的时候,会将文件中原来的数据进行覆盖
// FileOutputStream(String path,boolean bool):通过此构造方法创建的对象,
//并将构造方法第二个参数设置为true,使用write()方法写入数据的时候,数据写入在文件的末尾位置;第二个参数为false,写入内容会覆盖文件中原来的内容
// OutputStream os = new FileOutputStream("D:\\Test.txt"");
os = new FileOutputStream("D:\\Test.txt", true);
// 将数据写入到自定的文件中
os.write(11);
System.out.println("数据写入完毕");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
代码示例2
public static void main(String[] args) {
File file = new File("D:\\Test.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file,true);
//将一串字符写入文件中去
String str = "hello world";
byte[] bytes = str.getBytes();
fos.write(bytes);
System.out.println("数据写入完毕");
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意
/* * File类:操作文件或者目录属性的类
*
* InputStream:字节输入流,是一个抽象类,不能实例化
* FileInputStream:字节输入流,是InputStream的子类, 可以实例化
* 构造方法:
* FileInputStream(File file)
* FileInputStream(String path)
*
* OutputStream:字节输出流,是一个抽象类,不能实例化
* FileOutputStream:字节输出流,是一个抽象类,不能实例化
* 构造方法:
* FileOutputStream(File file)
* FileOutputStream(File file,boolean bool)
* FileOutputStream(String path)
* FileOutputStream((String path,boolean bool)
* */
2.4、字符流
2.4.1、Reader类
Reader类常用方法
- int read( )
- int read(char[] c)
- read(char[] c,int off,int len)
- void close( )
子类InputStreamReader常用的构造方法
- InputStreamReader(InputStream in)
- InputStreamReader(InputStream in,String charsetName)
FileReader类是InputStreamReader的子类
- FileReader(File file)
- FileReader(String name)
该类只能按照本地平台的字符编码来读取数据,用户不能指定其他的字符编码类型
System.out.println(System.getProperty(“file.encoding”)); 获得本地平台的字符编码类型
使用FileRedaer读取文件步骤
- 引入相关的类
import java.io.Reader;
import java.io.FileReader;
Import java.io.IOExceprion;
- 创建FileReader对象
Reader fr= new FileReader("D:\\demo.txt");
- 读取文本文件的数据
fr.read();
- 关闭相关的流对象
fr.close();
代码示例
import java.io.FileReader;
import java.io.IOException;
public class FileReaderDemo {
public static void main(String[] args) throws IOException {
FileReader fr = null;
fr = new FileReader("D:\\demo.txt");
//read()一个一个的读取文件夹字符
int num = fr.read();
System.out.println((char)num);
fr.close();
}
}
2.4.2、Writer类
Writer类常用方法
- write(String str)
- write(String str,int off,int len)
- void close()
- void flush()
子类OutputStreamWriter常用的构造方法
- OutputStreamWriter(OutputStream out)
- OutputStreamWriter(OutputStream out,String charsetName)
FileWriter类是OutputStreamWriter的子类
- FileWriter (File file)
- FileWriter (String name)
该类只能按照本地平台的字符编码来写数据,用户不能指定其他的字符编码类型
使用FileWriter写文件
- 引入相关的类
import java.io.Reader;
import java.io.FileWriter;
Import java.io.IOException;
- 创建FileReader对象
Writer fw= new FileWriter("D:\\demo.txt");
- 写文本文件
fw.writer();
- 关闭相关的流对象
fw.close();
代码示例
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterDemo01 {
public static void main(String[] args) throws IOException {
// 创建FileWriter类对象
FileWriter fw = null;
fw = new FileWriter("D:\\demo.txt", true);
fw.write("html,js,css");
System.out.println("写入成功");
fw.close();
}
}
2.5、缓冲流
2.2.1、缓冲字节流
1、缓冲输入流:BufferedInputStream
2、缓冲输出流:BufferedOutputStream
2.2.2、缓冲字符流
1、缓冲输入流:BufferedReader
BufferedReader类可以提高字符流读取文本文件的效率
BufferedReader类是Reader类的子类
BufferedReader类带有缓冲区
按行读取内容的readLine()方法
BufferedReader常用的构造方法
- BufferedReader(Reader in)
BufferedReader特有的方法
- readLine()
使用BufferedReader读文本文件步骤
- 引入相关的类
import java.io.FileReader;
import java.io.BufferedReader;
Import java.io.IOException;
- 创建BufferedReader对象和FileReader对象
Reader fr= new FileReader("C:\\demo.txt ");
BufferedReader br=new BufferedReader(fr);
- 调用readLine方法读取数据
br.ReadLine();
- 关闭相关的流对象
br.close();
fr.close();
代码示例
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class BufferedReaderDemo01 {
public static void main(String[] args) throws IOException {
// 创建BufferReader对象
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream("D:\\demo.txt"), "UTF-8"));
String str;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
}
}
2、缓冲输出流:BufferedWriter
BufferedWriter可以提高字符流写文本文件的效率
使用FileWriter类与BufferedWriter类
- BufferedWriter类是Writer类的子类
- BufferedWriter类带有缓冲区
BufferedWriter常用的构造方法
- BufferedWriter(Writer out)
使用BufferedReader读文本文件步骤
- 引入相关的类
import java.io.FileWriter;
import java.io.BufferedWriter;
Import java.io.IOException;
- 创建BufferedWriter对象和FileWriter对象
Writer fw= new FileWriter("C:\\demo.txt ");
BufferedWriter bw=new BufferedWriter(fw);
- 调用writer()方法读取数据
br.readLine();
- 关闭相关的流对象和清空
bw.flush();
fw.close();
代码示例
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class BufferedWriterDemo01 {
public static void main(String[] args) {
// 创建BufferedWriter类对象
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("D:\\demo.txt", true)));
bw.newLine();
bw.write("javjffffsasfsadasdsd");
bw.flush();
System.out.println("数据写入完毕");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.6、数据流
2.6.1、DateInputStream类
- FileInputStream的子类
- 与FileInputStream类结合使用读取二进制文件
使用DateInputStream读二进制文件步骤
- 引入相关的类
import java.io.FileInputStream;
import java.io.DataInputStream;
- 创建数据输入流对象
FileInputStream fis=new
FileInputStream("C:\\HelloWorld.class");
DataInputStream dis=new DataInputStream(fis);
- 调用read()方法读取二进制数据
dis.read();
- 关闭数据输入流
dis.close();
2.6.2、DateOutputStream类
- FileOutputStream的子类
- 与FileOutputStream类结合使用写二进制文件
使用DateInputStream读二进制文件步骤
- 引入相关的类
import java.io.FileOutputStream;
import java.io.DataOutputStream;
- 创建数据输入流对象
FileOutputStream fos=new
FileOutputStream("C:\\HelloWorld.class");
DataOutputStream dos=new DataOutputStream(fos);
- 调用writer()方法读取二进制数据
dos.writer();
- 关闭数据输入流
dos.close();
DateInputStream和DateOutputStream代码示例
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class DataInputStreamAndDataOutputStreamDemo01 {
public static void main(String[] args) {
//创建FileInputStream类对象
FileInputStream fis=null;
//创建DataInputStream类对象
DataInputStream dis =null;
//创建FileOutputStream类对象
FileOutputStream fos =null;
//创建DataOutputStream类对象
DataOutputStream dos = null;
try {
fis = new FileInputStream("F:/beautiful.jpg");
dis = new DataInputStream(fis);
fos = new FileOutputStream("F:/girl.jpg");
dos=new DataOutputStream(fos);
int num;
while((num=dis.read())!=-1){
dos.write(num);
}
System.out.println("图片复制完毕");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
dos.close();
fos.close();
dis.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.7、序列化
序列化和反序列化的过程
序列化是将对象的状态写入到特定的流中的过程
反序列化是从特定的流中获取数据重新构建对象的过程
实现序列化
- 实现Serializable接口
- 创建对象输出流
- 调用writerObject()方法
- 关闭对象输出流
注意:使用集合保存对象,可以将集合中的所有对象序列化
实现反序列化
- 实现Serializable接口
- 创建对象输入流
- 调用readObject()方法
- 关闭对象输出流
如果向文件中使用序列化机制写入多个对象,那么反序列化恢复对象时,必须按照写入的顺序读取
代码示例