古人云学而不思则罔 思而不学则殆,元旦最后一天假期没事就总结下javase中的常用方法吧。希望对大家有所帮助。
hasNestxx()//判断是否是梦中类型元素
nextxxx()//获取该元素
nextInt()//获取一个int类型的值
nextLine()//获取一个string的类型值
equals//比较的是内容是否相同//需要重写
-----------------------------------------------
StringBuffer
capacity();//返回当前容量
------------------------
集合:
set<k> keySet()//获取集合中所有键的集合
collection<v> values//获取集合中所有值得集合
set<map.entry<k,v>> entrySet()//
--------------------------
//遍历,
//获取所有的键
Set<String> set = map.keySet();
//遍历键的集合
for (String key : set) {
//根据键去找值
String value = (String) map.get(key);
System.out.println(key+"..."+value);
------------------------------------
Set<Entry<String,Object>> set = map.entrySet();
//遍历键值对集合得到每一个键值对对象
for (Entry<String, Object> me : set) {
//根据键值对对象获取键值
String key = me.getKey();
Object value = me.getValue();
System.out.println(key+"..."+value);
}
------------------------------------------------------
//创建集合对象
HashMap<String, HashMap<String, Integer>> czbkmap=new HashMap<String, HashMap<String, Integer>>();
//创建基础班
HashMap<String, Integer> jcmap=new HashMap<String, Integer>();
jcmap.put("cyl", 20);
jcmap.put("gy", 22);
czbkmap.put("jc", jcmap);
//创建就业班
HashMap<String, Integer> jymap=new HashMap<String, Integer>();
jymap.put("lj", 21);
jymap.put("csl", 23);
czbkmap.put("jy", jymap);
//遍历set集合
Set<String> czbkset = czbkmap.keySet();
for (String czbkkey : czbkset) {
System.err.println(czbkkey);
HashMap<String, Integer> czbkmapvalue = czbkmap.get(czbkkey);
Set<String> czbkMapValueSet = czbkmapvalue.keySet();
for (String czbkMapValueKey : czbkMapValueSet) {
Integer czbkMapValueValue = czbkmapvalue.get(czbkMapValueKey);
System.out.println(czbkMapValueKey+"..."+czbkMapValueValue);
}
}
--------------------
//创建集合
HashMap<String, ArrayList<String>> hm=new HashMap<String, ArrayList<String>>();
//创建元素集合1
ArrayList<String> array1=new ArrayList<String>();
array1.add("lvbu");
array1.add("zhouyu");
hm.put("sanguoyanyi", array1);
//创建元素集合2
ArrayList<String> array2=new ArrayList<String>();
array2.add("linghuchong");
array2.add("linpingzhi");
hm.put("xiaoaojiaohu", array2);
//创建元素集合3
ArrayList<String> array3=new ArrayList<String>();
array3.add("guojing");
array3.add("yangguo");
hm.put("shengdiaoxialv", array3);
//遍历
Set<String> set = hm.keySet();
for (String key : set) {
System.err.println(key);
ArrayList<String> value = hm.get(key);
for (String s : value) {
System.out.println("\t"+s);
}
}
--------------------------------
//创建集合arraylist嵌套hashmap
ArrayList<HashMap<String, String>> array=new ArrayList<HashMap<String, String>>();
//创建元素1
HashMap<String, String> hm1=new HashMap<>();
hm1.put("zhouyu", "xiaoqiao");
hm1.put("lvbu", "diaochan");
array.add(hm1);
//创建元素2
HashMap<String, String> hm2=new HashMap<>();
hm2.put("guojing", "huangrong");
hm2.put("yangguo", "xiaolonglv");
array.add(hm2);
//创建元素3
HashMap<String, String> hm3=new HashMap<>();
hm3.put("linghuchong", "renyingying");
hm3.put("lingpinzhi", "yuelingshan");
array.add(hm3);
//遍历
for (HashMap<String, String> hm : array) {
System.err.println("\t"+hm);
Set<String> set = hm.keySet();
for (String key : set) {
String value = hm.get(key);//通过key找到对应的value
System.out.println(key+"..."+value);
}
}
-----------------
传智播客
* bj 北京校区
* jc 基础班
* 林青霞 27
* 风清扬 30
* jy 就业班
* 赵雅芝 28
* 武鑫 29
* sh 上海校区
* jc 基础班
* 郭美美 20
* 犀利哥 22
* jy 就业班
* 罗玉凤 21
* 马征 23
* gz 广州校区
* jc 基础班
* 王力宏 30
* 李静磊 32
* jy 就业班
* 郎朗 31
* 柳岩 33
* xa 西安校区
* jc 基础班
* 范冰冰 27
* 刘意 30
* jy 就业班
* 李冰冰 28
* 张志豪 29
// 创建大集合
HashMap<String, HashMap<String, ArrayList<Student>>> czbkMap = new HashMap<String, HashMap<String, ArrayList<Student>>>();
// 北京校区数据
HashMap<String, ArrayList<Student>> bjCzbkMap = new HashMap<String, ArrayList<Student>>();
ArrayList<Student> array1 = new ArrayList<Student>();
Student s1 = new Student("林青霞", 27);
Student s2 = new Student("风清扬", 30);
array1.add(s1);
array1.add(s2);
ArrayList<Student> array2 = new ArrayList<Student>();
Student s3 = new Student("赵雅芝", 28);
Student s4 = new Student("武鑫", 29);
array2.add(s3);
array2.add(s4);
bjCzbkMap.put("基础班", array1);
bjCzbkMap.put("就业班", array2);
czbkMap.put("北京校区", bjCzbkMap);
// 西安校区数据
HashMap<String, ArrayList<Student>> xaCzbkMap = new HashMap<String, ArrayList<Student>>();
ArrayList<Student> array3 = new ArrayList<Student>();
Student s5 = new Student("范冰冰", 27);
Student s6 = new Student("刘意", 30);
array3.add(s5);
array3.add(s6);
ArrayList<Student> array4 = new ArrayList<Student>();
Student s7 = new Student("李冰冰", 28);
Student s8 = new Student("张志豪", 29);
array4.add(s7);
array4.add(s8);
xaCzbkMap.put("基础班", array3);
xaCzbkMap.put("就业班", array4);
czbkMap.put("西安校区", xaCzbkMap);
// 遍历集合
Set<String> czbkMapSet = czbkMap.keySet();
for (String czbkMapKey : czbkMapSet) {
System.out.println(czbkMapKey);
HashMap<String, ArrayList<Student>> czbkMapValue = czbkMap
.get(czbkMapKey);
Set<String> czbkMapValueSet = czbkMapValue.keySet();
for (String czbkMapValueKey : czbkMapValueSet) {
System.out.println("\t" + czbkMapValueKey);
ArrayList<Student> czbkMapValueValue = czbkMapValue
.get(czbkMapValueKey);
for (Student s : czbkMapValueValue) {
System.out.println("\t\t" + s.getName() + "---"
+ s.getAge());
}
}
}
--------------------------------
//io
* boolean createNewFile()//创建文件
* boolean mkdir()//创建文件夹如果存在返回false
* boolean mkdirs()//创建文件夹如果父文件夹不存在会自动创建
//需要在目录下创建内容,改目录首先必须存在
File file=new File("e:\\filedemo");
file.mkdir();
File file2=new File("e:\\filedemo\\a.txt");
file2.createNewFile();
* 判断功能:
* public boolean isDirectory():判断是否是目录
* public boolean isFile():判断是否是文件
* public boolean exists():判断是否存在
* public boolean canRead():判断是否可读
* public boolean canWrite():判断是否可写
* public boolean isHidden():判断是否隐藏
* 获取功能:
* public String getAbsolutePath():获取绝对路径
* public String getPath():获取相对路径
* public String getName():获取名称
* public long length():获取长度。字节数
* public long lastModified():获取最后一次的修改时间,毫秒值
* 获取功能:
* public String[] list():获取指定目录下的所有文件或者文件夹的名称数组
* public File[] listFiles():获取指定目录下的所有文件或者文件夹的File数组
// 指定一个目录
File file = new File("e:\\");
String[] strArray = file.list();
for (String s : strArray) {
System.out.println(s);
}
-----------------------
File[] fileArray = file.listFiles();
for (File f : fileArray) {
System.out.println(f.getName());
}
* 判断E盘目录下是否有后缀名为.jpg的文件,如果有,就输出此文件名称
*
* 分析:
* A:封装e判断目录
* B:获取该目录下所有文件或者文件夹的File数组
* C:遍历该File数组,得到每一个File对象,然后判断
* D:是否是文件
* 是:继续判断是否以.jpg结尾
* 是:就输出该文件名称
* 否:不搭理它
* 否:不搭理它
// 封装e判断目录
File file = new File("e:\\");
// 获取该目录下所有文件或者文件夹的File数组
File[] fileArray = file.listFiles();
// 遍历该File数组,得到每一个File对象,然后判断
for (File f : fileArray) {
// 是否是文件
if (f.isFile()) {
// 继续判断是否以.jpg结尾
if (f.getName().endsWith(".jpg")) {
// 就输出该文件名称
System.out.println(f.getName());
}
}
}
--------
// 封装e判断目录
File file = new File("e:\\");
// 获取该目录下所有文件或者文件夹的String数组
// public String[] list(FilenameFilter filter)
String[] strArray = file.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
// return false;
// return true;
// 通过这个测试,我们就知道了,到底把这个文件或者文件夹的名称加不加到数组中,取决于这里的返回值是true还是false
// 所以,这个的true或者false应该是我们通过某种判断得到的
// System.out.println(dir + "---" + name);
// File file = new File(dir, name);
// // System.out.println(file);
// boolean flag = file.isFile();
// boolean flag2 = name.endsWith(".jpg");
// return flag && flag2;
return new File(dir, name).isFile() && name.endsWith(".jpg");
}
});
// 遍历
for (String s : strArray) {
System.out.println(s);
}
* 需求:把E:\评书\三国演义下面的视频名称修改为
* 00?_介绍.avi
*
* 思路:
* A:封装目录
* B:获取该目录下所有的文件的File数组
* C:遍历该File数组,得到每一个File对象
* D:拼接一个新的名称,然后重命名即可。
public class FileDemo {
public static void main(String[] args) {
// 封装目录
File srcFolder = new File("E:\\评书\\三国演义");
// 获取该目录下所有的文件的File数组
File[] fileArray = srcFolder.listFiles();
// 遍历该File数组,得到每一个File对象
for (File file : fileArray) {
// System.out.println(file);
// E:\评书\三国演义\三国演义_001_[评书网-今天很高兴,明天就IO了]_桃园三结义.avi
// 改后:E:\评书\三国演义\001_桃园三结义.avi
String name = file.getName(); // 三国演义_001_[评书网-今天很高兴,明天就IO了]_桃园三结义.avi
int index = name.indexOf("_");
String numberString = name.substring(index + 1, index + 4);
// System.out.println(numberString);
// int startIndex = name.lastIndexOf('_');
// int endIndex = name.lastIndexOf('.');
// String nameString = name.substring(startIndex + 1, endIndex);
// System.out.println(nameString);
int endIndex = name.lastIndexOf('_');
String nameString = name.substring(endIndex);
String newName = numberString.concat(nameString); // 001_桃园三结义.avi
// System.out.println(newName);
File newFile = new File(srcFolder, newName); // E:\\评书\\三国演义\\001_桃园三结义.avi
// 重命名即可
file.renameTo(newFile);
}
}
}
----------------------------------------------------------------
//递归:
* 有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问第二十个月的兔子对数为多少?
* 分析:我们要想办法找规律
* 兔子对数
* 第一个月: 1
* 第二个月: 1
* 第三个月: 2
* 第四个月: 3
* 第五个月: 5
* 第六个月: 8
* ...
*
* 由此可见兔子对象的数据是:
* 1,1,2,3,5,8...
* 规则:
* A:从第三项开始,每一项是前两项之和
* B:而且说明前两项是已知的
*
* 如何实现这个程序呢?
* A:数组实现
* B:变量的变化实现
* C:递归实现
*
* 假如相邻的两个月的兔子对数是a,b
* 第一个相邻的数据:a=1,b=1
* 第二个相邻的数据:a=1,b=2
* 第三个相邻的数据:a=2,b=3
* 第四个相邻的数据:a=3,b=5
* 看到了:下一次的a是以前的b,下一次是以前的a+b
public class DiGuiDemo2 {
public static void main(String[] args) {
// 定义一个数组
int[] arr = new int[20];
arr[0] = 1;
arr[1] = 1;
// arr[2] = arr[0] + arr[1];
// arr[3] = arr[1] + arr[2];
// ...
for (int x = 2; x < arr.length; x++) {
arr[x] = arr[x - 2] + arr[x - 1];
}
System.out.println(arr[19]);// 6765
System.out.println("----------------");
int a = 1;
int b = 1;
for (int x = 0; x < 18; x++) {
// 临时变量存储上一次的a
int temp = a;
a = b;
b = temp + b;
}
System.out.println(b);
System.out.println("----------------");
System.out.println(fib(20));
}
/*
* 方法: 返回值类型:int 参数列表:int n 出口条件: 第一个月是1,第二个月是1 规律: 从第三个月开始,每一个月是前两个月之和
*/
public static int fib(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return fib(n - 1) + fib(n - 2);
}
}
}
* 需求:请大家把E:\JavaSE目录下所有的java结尾的文件的绝对路径给输出在控制台。
*
* 分析:
* A:封装目录
* B:获取该目录下所有的文件或者文件夹的File数组
* C:遍历该File数组,得到每一个File对象
* D:判断该File对象是否是文件夹
* 是:回到B
* 否:继续判断是否以.java结尾
* 是:就输出该文件的绝对路径
* 否:不搭理它
public class FilePathDemo {
public static void main(String[] args) {
// 封装目录
File srcFolder = new File("E:\\JavaSE");
// 递归功能实现
getAllJavaFilePaths(srcFolder);
}
private static void getAllJavaFilePaths(File srcFolder) {
// 获取该目录下所有的文件或者文件夹的File数组
File[] fileArray = srcFolder.listFiles();
// 遍历该File数组,得到每一个File对象
for (File file : fileArray) {
// 判断该File对象是否是文件夹
if (file.isDirectory()) {
getAllJavaFilePaths(file);
} else {
// 继续判断是否以.java结尾
if (file.getName().endsWith(".java")) {
// 就输出该文件的绝对路径
System.out.println(file.getAbsolutePath());
}
}
}
}
}
-----------------2.0----------------------------------------------
输入流--读数据,输出流--写入数据
* IO流的分类:
* 流向:
* 输入流 读取数据
* 输出流 写出数据
* 数据类型:
* 字节流
* 字节输入流 读取数据 InputStream
* 字节输出流 写出数据 OutputStream
* 字符流
* 字符输入流 读取数据 Reader
* 字符输出流 写出数据 Writer
*
* 注意:一般我们在探讨IO流的时候,如果没有明确说明按哪种分类来说,默认情况下是按照数据类型来分的。
*
* 需求:我要往一个文本文件中输入一句话:"hello,io"
*
* 分析:
* A:这个操作最好是采用字符流来做,但是呢,字符流是在字节流之后才出现的,所以,今天我先讲解字节流如何操作。
* B:由于我是要往文件中写一句话,所以我们要采用字节输出流。
*
* 通过上面的分析后我们知道要使用:OutputStream
* 但是通过查看API,我们发现该流对象是一个抽象类,不能实例化。
* 所以,我们要找一个具体的子类。
* 而我们要找的子类是什么名字的呢?这个时候,很简单,我们回想一下,我们是不是要往文件中写东西。
* 文件是哪个单词:File
* 然后用的是字节输出流,联起来就是:FileOutputStream
* 注意:每种基类的子类都是以父类名作为后缀名。
* XxxOutputStream
* XxxInputStream
* XxxReader
* XxxWriter
* 查看FileOutputStream的构造方法:
* FileOutputStream(File file)
* FileOutputStream(String name)
*
* 字节输出流操作步骤:
* A:创建字节输出流对象
* B:写数据
* C:释放资源
public class FileOutputStreamDemo {
public static void main(String[] args) throws IOException {
// 创建字节输出流对象
// FileOutputStream(File file)
// File file = new File("fos.txt");
// FileOutputStream fos = new FileOutputStream(file);
// FileOutputStream(String name)
FileOutputStream fos = new FileOutputStream("fos.txt");
/*
* 创建字节输出流对象了做了几件事情:
* A:调用系统功能去创建文件
* B:创建fos对象
* C:把fos对象指向这个文件
*/
//写数据
fos.write("hello,IO".getBytes());
fos.write("java".getBytes());
//释放资源
//关闭此文件输出流并释放与此流有关的所有系统资源。
fos.close();
/*
* 为什么一定要close()呢?
* A:让流对象变成垃圾,这样就可以被垃圾回收器回收了
* B:通知系统去释放跟该文件相关的资源
*/
//java.io.IOException: Stream Closed
//fos.write("java".getBytes());
}
}
* 字节输入流操作步骤:
* A:创建字节输入流对象
* B:调用read()方法读取数据,并把数据显示在控制台
* C:释放资源
*
* 读取数据的方式:
* A:int read():一次读取一个字节
* B:int read(byte[] b):一次读取一个字节数组
int by=0;
while((by=fis.read()) !=-1){
System.out.print((char)by);
}
fis.close();
* 复制文本文件。
*
* 数据源:从哪里来
* a.txt -- 读取数据 -- FileInputStream
*
* 目的地:到哪里去
* b.txt -- 写数据 -- FileOutputStream
*
* java.io.FileNotFoundException: a.txt (系统找不到指定的文件。)
*
* 这一次复制中文没有出现任何问题,为什么呢?
* 上一次我们出现问题的原因在于我们每次获取到一个字节数据,就把该字节数据转换为了字符数据,然后输出到控制台。
* 而这一次呢?确实通过IO流读取数据,写到文本文件,你读取一个字节,我就写入一个字节,你没有做任何的转换。
* 它会自己做转换。
FileInputStream fis=new FileInputStream("fos.txt");
FileOutputStream fos=new FileOutputStream("b.txt");
int by=0;
while((by=fis.read()) != -1){
fos.write(by);
}
fis.close();
fos.close();
------------------------
// 数组的长度一般是1024或者1024的整数倍
byte[] bys = new byte[1024];
int len = 0;
while ((len = fis.read(bys)) != -1) {
System.out.print(new String(bys, 0, len));
}
// 释放资源
fis.close();
*将b.txt复制到c.txt
//封装数据源
FileReader fr=new FileReader("b.txt");
FileWriter fw=new FileWriter("c.txt");
char [] chs=new char[1024];
int len=0;
while((len=fr.read(chs)) != -1){
fw.write(chs,0,len);
}
fr.close();
fw.close();
* 字符流为了高效读写,也提供了对应的字符缓冲流。
* BufferedWriter:字符缓冲输出流
* BufferedReader:字符缓冲输入流
*
* BufferedWriter:字符缓冲输出流
* 将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。
* 可以指定缓冲区的大小,或者接受默认的大小。在大多数情况下,默认值就足够大了。
BufferedWriter bw=new BufferedWriter(new FileWriter("c.txt"));
bw.write("nihao");
bw.write("ma?");
bw.flush();
bw.close();
***读取c.txt的内容
BufferedReader bw=new BufferedReader(new FileReader("c.txt"));
char[] chs=new char[1024];
int len=0;
while((len=bw.read(chs)) != -1){
System.out.print(new String(chs, 0, len));
}
bw.close();
* 字符缓冲流的特殊方法:
* BufferedWriter:
* public void newLine():根据系统来决定换行符
* BufferedReader:
* public String readLine():一次读取一行数据
* 包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回 null
*吧c.txt复制到d.txt
BufferedReader br=new BufferedReader(new FileReader("c.txt"));
BufferedWriter bw=new BufferedWriter(new FileWriter("d.txt"));
String inne=null;
while((inne=br.readLine()) != null){
bw.write(inne);
bw.newLine();
bw.flush();
}
br.close();
bw.close();
* 需求:我有一个文本文件中存储了几个名称,请大家写一个程序实现随机获取一个人的名字。
*
* 分析:
* A:把文本文件中的数据存储到集合中
* B:随机产生一个索引
* C:根据该索引获取一个值
// 把文本文件中的数据存储到集合中
BufferedReader br = new BufferedReader(new FileReader("b.txt"));
ArrayList<String> array = new ArrayList<String>();
String line = null;
while ((line = br.readLine()) != null) {
array.add(line);
}
br.close();
// 随机产生一个索引
Random r = new Random();
int index = r.nextInt(array.size());
// 根据该索引获取一个值
String name = array.get(index);
System.out.println("该幸运者是:" + name);
* 需求:复制单极文件夹
*
* 数据源:e:\\demo
* 目的地:e:\\test
*
* 分析:
* A:封装目录
* B:获取该目录下的所有文本的File数组
* C:遍历该File数组,得到每一个File对象
* D:把该File进行复制
// 封装目录
File srcFolder = new File("e:\\demo");
// 封装目的地
File destFolder = new File("e:\\test");
// 如果目的地文件夹不存在,就创建
if (!destFolder.exists()) {
destFolder.mkdir();
}
// 获取该目录下的所有文本的File数组
File[] fileArray = srcFolder.listFiles();
// 遍历该File数组,得到每一个File对象
for (File file : fileArray) {
// System.out.println(file);
// 数据源:e:\\demo\\e.mp3
// 目的地:e:\\test\\e.mp3
String name = file.getName(); // e.mp3
File newFile = new File(destFolder, name); // e:\\test\\e.mp3
copyFile(file, newFile);
}
}
private static void copyFile(File file, File newFile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
file));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(newFile));
byte[] bys = new byte[1024];
int len = 0;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
bos.close();
bis.close();
}
* 需求:复制指定目录下的指定文件,并修改后缀名。
* 指定的文件是:.java文件。
* 指定的后缀名是:.jad
* 指定的目录是:jad
*
* 数据源:e:\\java\\A.java
* 目的地:e:\\jad\\A.jad
*
* 分析:
* A:封装目录
* B:获取该目录下的java文件的File数组
* C:遍历该File数组,得到每一个File对象
* D:把该File进行复制
* E:在目的地目录下改名
public class CopyFolderDemo {
public static void main(String[] args) throws IOException {
// 封装目录
File srcFolder = new File("e:\\java");
// 封装目的地
File destFolder = new File("e:\\jad");
// 如果目的地目录不存在,就创建
if (!destFolder.exists()) {
destFolder.mkdir();
}
// 获取该目录下的java文件的File数组
File[] fileArray = srcFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return new File(dir, name).isFile() && name.endsWith(".java");
}
});
// 遍历该File数组,得到每一个File对象
for (File file : fileArray) {
// System.out.println(file);
// 数据源:e:\java\DataTypeDemo.java
// 目的地:e:\\jad\DataTypeDemo.java
String name = file.getName();
File newFile = new File(destFolder, name);
copyFile(file, newFile);
}
// 在目的地目录下改名
File[] destFileArray = destFolder.listFiles();
for (File destFile : destFileArray) {
// System.out.println(destFile);
// e:\jad\DataTypeDemo.java
// e:\\jad\\DataTypeDemo.jad
String name =destFile.getName(); //DataTypeDemo.java
String newName = name.replace(".java", ".jad");//DataTypeDemo.jad
File newFile = new File(destFolder,newName);
destFile.renameTo(newFile);
}
}
private static void copyFile(File file, File newFile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
file));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(newFile));
byte[] bys = new byte[1024];
int len = 0;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
bos.close();
bis.close();
}
}
* 需求:复制多极文件夹
*
* 数据源:E:\JavaSE\day21\code\demos
* 目的地:E:\\
*
* 分析:
* A:封装数据源File
* B:封装目的地File
* C:判断该File是文件夹还是文件
* a:是文件夹
* 就在目的地目录下创建该文件夹
* 获取该File对象下的所有文件或者文件夹File对象
* 遍历得到每一个File对象
* 回到C
* b:是文件
* 就复制(字节流)
public class CopyFoldersDemo {
public static void main(String[] args) throws IOException {
// 封装数据源File
File srcFile = new File("E:\\JavaSE\\day21\\code\\demos");
// 封装目的地File
File destFile = new File("E:\\");
// 复制文件夹的功能
copyFolder(srcFile, destFile);
}
private static void copyFolder(File srcFile, File destFile)
throws IOException {
// 判断该File是文件夹还是文件
if (srcFile.isDirectory()) {
// 文件夹
File newFolder = new File(destFile, srcFile.getName());
newFolder.mkdir();
// 获取该File对象下的所有文件或者文件夹File对象
File[] fileArray = srcFile.listFiles();
for (File file : fileArray) {
copyFolder(file, newFolder);
}
} else {
// 文件
File newFile = new File(destFile, srcFile.getName());
copyFile(srcFile, newFile);
}
}
private static void copyFile(File srcFile, File newFile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
srcFile));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(newFile));
byte[] bys = new byte[1024];
int len = 0;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
bos.close();
bis.close();
}
}
------------------------------------
demo:
* 键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低存入文本文件
*
* 分析:
* A:创建学生类
* B:创建集合对象
* TreeSet<Student>
* C:键盘录入学生信息存储到集合
* D:遍历集合,把数据写到文本文件
*/
public class StudentDemo {
public static void main(String[] args) throws IOException {
// 创建集合对象
TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num = s2.getSum() - s1.getSum();
int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num;
int num3 = num2 == 0 ? s1.getMath() - s2.getMath() : num2;
int num4 = num3 == 0 ? s1.getEnglish() - s2.getEnglish() : num3;
int num5 = num4 == 0 ? s1.getName().compareTo(s2.getName())
: num4;
return num5;
}
});
// 键盘录入学生信息存储到集合
for (int x = 1; x <= 5; x++) {
Scanner sc = new Scanner(System.in);
System.out.println("请录入第" + x + "个的学习信息");
System.out.println("姓名:");
String name = sc.nextLine();
System.out.println("语文成绩:");
int chinese = sc.nextInt();
System.out.println("数学成绩:");
int math = sc.nextInt();
System.out.println("英语成绩:");
int english = sc.nextInt();
// 创建学生对象
Student s = new Student();
s.setName(name);
s.setChinese(chinese);
s.setMath(math);
s.setEnglish(english);
// 把学生信息添加到集合
ts.add(s);
}
// 遍历集合,把数据写到文本文件
BufferedWriter bw = new BufferedWriter(new FileWriter("students.txt"));
bw.write("学生信息如下:");
bw.newLine();
bw.flush();
bw.write("姓名,语文成绩,数学成绩,英语成绩");
bw.newLine();
bw.flush();
for (Student s : ts) {
StringBuilder sb = new StringBuilder();
sb.append(s.getName()).append(",").append(s.getChinese())
.append(",").append(s.getMath()).append(",")
.append(s.getEnglish());
bw.write(sb.toString());
bw.newLine();
bw.flush();
}
// 释放资源
bw.close();
System.out.println("学习信息存储完毕");
}
}
public class Student {
private String name;
private int chinese;
private int math;
private int english;
public int getSum() {
return this.chinese + this.math + this.english;
}
}
* 已知s.txt文件中有这样的一个字符串:“hcexfgijkamdnoqrzstuvwybpl”
* 请编写程序读取数据内容,把数据排序后写入ss.txt中。
*
* 分析:
* A:把s.txt这个文件给做出来
* B:读取该文件的内容,存储到一个字符串中
* C:把字符串转换为字符数组
* D:对字符数组进行排序
* E:把排序后的字符数组转换为字符串
* F:把字符串再次写入ss.txt中
// 读取该文件的内容,存储到一个字符串中
BufferedReader br = new BufferedReader(new FileReader("s.txt"));
String line = br.readLine();
br.close();
// 把字符串转换为字符数组
char[] chs = line.toCharArray();
// 对字符数组进行排序
Arrays.sort(chs);
// 把排序后的字符数组转换为字符串
String s = new String(chs);
// 把字符串再次写入ss.txt中
BufferedWriter bw = new BufferedWriter(new FileWriter("ss.txt"));
bw.write(s);
bw.newLine();
bw.flush();
bw.close();
* 用Reader模拟BufferedReader的readLine()功能
*
* readLine():一次读取一行,根据换行符判断是否结束,只返回内容,不返回换行符
public class MyBufferedReader {
private Reader r;
public MyBufferedReader(Reader r) {
this.r = r;
}
/*
* 思考:写一个方法,返回值是一个字符串。
*/
public String readLine() throws IOException {
/*
* 我要返回一个字符串,我该怎么办呢? 我们必须去看看r对象能够读取什么东西呢? 两个读取方法,一次读取一个字符或者一次读取一个字符数组
* 那么,我们要返回一个字符串,用哪个方法比较好呢? 我们很容易想到字符数组比较好,但是问题来了,就是这个数组的长度是多长呢?
* 根本就没有办法定义数组的长度,你定义多长都不合适。 所以,只能选择一次读取一个字符。
* 但是呢,这种方式的时候,我们再读取下一个字符的时候,上一个字符就丢失了 所以,我们又应该定义一个临时存储空间把读取过的字符给存储起来。
* 这个用谁比较和是呢?数组,集合,字符串缓冲区三个可供选择。
* 经过简单的分析,最终选择使用字符串缓冲区对象。并且使用的是StringBuilder
*/
StringBuilder sb = new StringBuilder();
// 做这个读取最麻烦的是判断结束,但是在结束之前应该是一直读取,直到-1
/*
hello
world
java
104101108108111
119111114108100
1069711897
*/
int ch = 0;
while ((ch = r.read()) != -1) { //104,101,108,108,111
if (ch == '\r') {
continue;
}
if (ch == '\n') {
return sb.toString(); //hello
} else {
sb.append((char)ch); //hello
}
}
// 为了防止数据丢失,判断sb的长度不能大于0
if (sb.length() > 0) {
return sb.toString();
}
return null;
}
/*
* 先写一个关闭方法
*/
public void close() throws IOException {
this.r.close();
}
}
* 测试MyBufferedReader的时候,你就把它当作BufferedReader一样的使用
public class MyBufferedReaderDemo {
public static void main(String[] args) throws IOException {
MyBufferedReader mbr = new MyBufferedReader(new FileReader("my.txt"));
String line = null;
while ((line = mbr.readLine()) != null) {
System.out.println(line);
}
mbr.close();
// System.out.println('\r' + 0); // 13
// System.out.println('\n' + 0);// 10
}
}
* 需求:DataStreamDemo.java复制到Copy.java中
* 数据源:
* DataStreamDemo.java -- 读取数据 -- FileReader -- BufferedReader
* 目的地:
* Copy.java -- 写出数据 -- FileWriter -- BufferedWriter -- PrintWriter
public class CopyFileDemo {
public static void main(String[] args) throws IOException {
// 以前的版本
// 封装数据源
// BufferedReader br = new BufferedReader(new FileReader(
// "DataStreamDemo.java"));
// // 封装目的地
// BufferedWriter bw = new BufferedWriter(new FileWriter("Copy.java"));
//
// String line = null;
// while ((line = br.readLine()) != null) {
// bw.write(line);
// bw.newLine();
// bw.flush();
// }
//
// bw.close();
// br.close();
// 打印流的改进版
// 封装数据源
BufferedReader br = new BufferedReader(new FileReader(
"DataStreamDemo.java"));
// 封装目的地
PrintWriter pw = new PrintWriter(new FileWriter("Copy.java"), true);
String line = null;
while((line=br.readLine())!=null){
pw.println(line);
}
pw.close();
br.close();
}
}
* 我有一个文本文件(user.txt),我知道数据是键值对形式的,但是不知道内容是什么。
* 请写一个程序判断是否有“lisi”这样的键存在,如果有就改变其实为”100”
*
* 分析:
* A:把文件中的数据加载到集合中
* B:遍历集合,获取得到每一个键
* C:判断键是否有为"lisi"的,如果有就修改
public class PropertiesTest {
public static void main(String[] args) throws IOException {
// 把文件中的数据加载到集合中
Properties prop = new Properties();
Reader r = new FileReader("user.txt");
prop.load(r);
r.close();
// 遍历集合,获取得到每一个键
Set<String> set = prop.stringPropertyNames();
for (String key : set) {
// 判断键是否有为"lisi"的,如果有就修改其值为"100"
if ("lisi".equals(key)) {
prop.setProperty(key, "100");
break;
}
}
// 把集合中的数据重新存储到文件中
Writer w = new FileWriter("user.txt");
prop.store(w, null);
w.close();
}
}
nextxxx()//获取该元素
nextInt()//获取一个int类型的值
nextLine()//获取一个string的类型值
equals//比较的是内容是否相同//需要重写
-----------------------------------------------
StringBuffer
capacity();//返回当前容量
------------------------
集合:
set<k> keySet()//获取集合中所有键的集合
collection<v> values//获取集合中所有值得集合
set<map.entry<k,v>> entrySet()//
--------------------------
//遍历,
//获取所有的键
Set<String> set = map.keySet();
//遍历键的集合
for (String key : set) {
//根据键去找值
String value = (String) map.get(key);
System.out.println(key+"..."+value);
------------------------------------
Set<Entry<String,Object>> set = map.entrySet();
//遍历键值对集合得到每一个键值对对象
for (Entry<String, Object> me : set) {
//根据键值对对象获取键值
String key = me.getKey();
Object value = me.getValue();
System.out.println(key+"..."+value);
}
------------------------------------------------------
//创建集合对象
HashMap<String, HashMap<String, Integer>> czbkmap=new HashMap<String, HashMap<String, Integer>>();
//创建基础班
HashMap<String, Integer> jcmap=new HashMap<String, Integer>();
jcmap.put("cyl", 20);
jcmap.put("gy", 22);
czbkmap.put("jc", jcmap);
//创建就业班
HashMap<String, Integer> jymap=new HashMap<String, Integer>();
jymap.put("lj", 21);
jymap.put("csl", 23);
czbkmap.put("jy", jymap);
//遍历set集合
Set<String> czbkset = czbkmap.keySet();
for (String czbkkey : czbkset) {
System.err.println(czbkkey);
HashMap<String, Integer> czbkmapvalue = czbkmap.get(czbkkey);
Set<String> czbkMapValueSet = czbkmapvalue.keySet();
for (String czbkMapValueKey : czbkMapValueSet) {
Integer czbkMapValueValue = czbkmapvalue.get(czbkMapValueKey);
System.out.println(czbkMapValueKey+"..."+czbkMapValueValue);
}
}
--------------------
//创建集合
HashMap<String, ArrayList<String>> hm=new HashMap<String, ArrayList<String>>();
//创建元素集合1
ArrayList<String> array1=new ArrayList<String>();
array1.add("lvbu");
array1.add("zhouyu");
hm.put("sanguoyanyi", array1);
//创建元素集合2
ArrayList<String> array2=new ArrayList<String>();
array2.add("linghuchong");
array2.add("linpingzhi");
hm.put("xiaoaojiaohu", array2);
//创建元素集合3
ArrayList<String> array3=new ArrayList<String>();
array3.add("guojing");
array3.add("yangguo");
hm.put("shengdiaoxialv", array3);
//遍历
Set<String> set = hm.keySet();
for (String key : set) {
System.err.println(key);
ArrayList<String> value = hm.get(key);
for (String s : value) {
System.out.println("\t"+s);
}
}
--------------------------------
//创建集合arraylist嵌套hashmap
ArrayList<HashMap<String, String>> array=new ArrayList<HashMap<String, String>>();
//创建元素1
HashMap<String, String> hm1=new HashMap<>();
hm1.put("zhouyu", "xiaoqiao");
hm1.put("lvbu", "diaochan");
array.add(hm1);
//创建元素2
HashMap<String, String> hm2=new HashMap<>();
hm2.put("guojing", "huangrong");
hm2.put("yangguo", "xiaolonglv");
array.add(hm2);
//创建元素3
HashMap<String, String> hm3=new HashMap<>();
hm3.put("linghuchong", "renyingying");
hm3.put("lingpinzhi", "yuelingshan");
array.add(hm3);
//遍历
for (HashMap<String, String> hm : array) {
System.err.println("\t"+hm);
Set<String> set = hm.keySet();
for (String key : set) {
String value = hm.get(key);//通过key找到对应的value
System.out.println(key+"..."+value);
}
}
-----------------
传智播客
* bj 北京校区
* jc 基础班
* 林青霞 27
* 风清扬 30
* jy 就业班
* 赵雅芝 28
* 武鑫 29
* sh 上海校区
* jc 基础班
* 郭美美 20
* 犀利哥 22
* jy 就业班
* 罗玉凤 21
* 马征 23
* gz 广州校区
* jc 基础班
* 王力宏 30
* 李静磊 32
* jy 就业班
* 郎朗 31
* 柳岩 33
* xa 西安校区
* jc 基础班
* 范冰冰 27
* 刘意 30
* jy 就业班
* 李冰冰 28
* 张志豪 29
// 创建大集合
HashMap<String, HashMap<String, ArrayList<Student>>> czbkMap = new HashMap<String, HashMap<String, ArrayList<Student>>>();
// 北京校区数据
HashMap<String, ArrayList<Student>> bjCzbkMap = new HashMap<String, ArrayList<Student>>();
ArrayList<Student> array1 = new ArrayList<Student>();
Student s1 = new Student("林青霞", 27);
Student s2 = new Student("风清扬", 30);
array1.add(s1);
array1.add(s2);
ArrayList<Student> array2 = new ArrayList<Student>();
Student s3 = new Student("赵雅芝", 28);
Student s4 = new Student("武鑫", 29);
array2.add(s3);
array2.add(s4);
bjCzbkMap.put("基础班", array1);
bjCzbkMap.put("就业班", array2);
czbkMap.put("北京校区", bjCzbkMap);
// 西安校区数据
HashMap<String, ArrayList<Student>> xaCzbkMap = new HashMap<String, ArrayList<Student>>();
ArrayList<Student> array3 = new ArrayList<Student>();
Student s5 = new Student("范冰冰", 27);
Student s6 = new Student("刘意", 30);
array3.add(s5);
array3.add(s6);
ArrayList<Student> array4 = new ArrayList<Student>();
Student s7 = new Student("李冰冰", 28);
Student s8 = new Student("张志豪", 29);
array4.add(s7);
array4.add(s8);
xaCzbkMap.put("基础班", array3);
xaCzbkMap.put("就业班", array4);
czbkMap.put("西安校区", xaCzbkMap);
// 遍历集合
Set<String> czbkMapSet = czbkMap.keySet();
for (String czbkMapKey : czbkMapSet) {
System.out.println(czbkMapKey);
HashMap<String, ArrayList<Student>> czbkMapValue = czbkMap
.get(czbkMapKey);
Set<String> czbkMapValueSet = czbkMapValue.keySet();
for (String czbkMapValueKey : czbkMapValueSet) {
System.out.println("\t" + czbkMapValueKey);
ArrayList<Student> czbkMapValueValue = czbkMapValue
.get(czbkMapValueKey);
for (Student s : czbkMapValueValue) {
System.out.println("\t\t" + s.getName() + "---"
+ s.getAge());
}
}
}
--------------------------------
//io
* boolean createNewFile()//创建文件
* boolean mkdir()//创建文件夹如果存在返回false
* boolean mkdirs()//创建文件夹如果父文件夹不存在会自动创建
//需要在目录下创建内容,改目录首先必须存在
File file=new File("e:\\filedemo");
file.mkdir();
File file2=new File("e:\\filedemo\\a.txt");
file2.createNewFile();
* 判断功能:
* public boolean isDirectory():判断是否是目录
* public boolean isFile():判断是否是文件
* public boolean exists():判断是否存在
* public boolean canRead():判断是否可读
* public boolean canWrite():判断是否可写
* public boolean isHidden():判断是否隐藏
* 获取功能:
* public String getAbsolutePath():获取绝对路径
* public String getPath():获取相对路径
* public String getName():获取名称
* public long length():获取长度。字节数
* public long lastModified():获取最后一次的修改时间,毫秒值
* 获取功能:
* public String[] list():获取指定目录下的所有文件或者文件夹的名称数组
* public File[] listFiles():获取指定目录下的所有文件或者文件夹的File数组
// 指定一个目录
File file = new File("e:\\");
String[] strArray = file.list();
for (String s : strArray) {
System.out.println(s);
}
-----------------------
File[] fileArray = file.listFiles();
for (File f : fileArray) {
System.out.println(f.getName());
}
* 判断E盘目录下是否有后缀名为.jpg的文件,如果有,就输出此文件名称
*
* 分析:
* A:封装e判断目录
* B:获取该目录下所有文件或者文件夹的File数组
* C:遍历该File数组,得到每一个File对象,然后判断
* D:是否是文件
* 是:继续判断是否以.jpg结尾
* 是:就输出该文件名称
* 否:不搭理它
* 否:不搭理它
// 封装e判断目录
File file = new File("e:\\");
// 获取该目录下所有文件或者文件夹的File数组
File[] fileArray = file.listFiles();
// 遍历该File数组,得到每一个File对象,然后判断
for (File f : fileArray) {
// 是否是文件
if (f.isFile()) {
// 继续判断是否以.jpg结尾
if (f.getName().endsWith(".jpg")) {
// 就输出该文件名称
System.out.println(f.getName());
}
}
}
--------
// 封装e判断目录
File file = new File("e:\\");
// 获取该目录下所有文件或者文件夹的String数组
// public String[] list(FilenameFilter filter)
String[] strArray = file.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
// return false;
// return true;
// 通过这个测试,我们就知道了,到底把这个文件或者文件夹的名称加不加到数组中,取决于这里的返回值是true还是false
// 所以,这个的true或者false应该是我们通过某种判断得到的
// System.out.println(dir + "---" + name);
// File file = new File(dir, name);
// // System.out.println(file);
// boolean flag = file.isFile();
// boolean flag2 = name.endsWith(".jpg");
// return flag && flag2;
return new File(dir, name).isFile() && name.endsWith(".jpg");
}
});
// 遍历
for (String s : strArray) {
System.out.println(s);
}
* 需求:把E:\评书\三国演义下面的视频名称修改为
* 00?_介绍.avi
*
* 思路:
* A:封装目录
* B:获取该目录下所有的文件的File数组
* C:遍历该File数组,得到每一个File对象
* D:拼接一个新的名称,然后重命名即可。
public class FileDemo {
public static void main(String[] args) {
// 封装目录
File srcFolder = new File("E:\\评书\\三国演义");
// 获取该目录下所有的文件的File数组
File[] fileArray = srcFolder.listFiles();
// 遍历该File数组,得到每一个File对象
for (File file : fileArray) {
// System.out.println(file);
// E:\评书\三国演义\三国演义_001_[评书网-今天很高兴,明天就IO了]_桃园三结义.avi
// 改后:E:\评书\三国演义\001_桃园三结义.avi
String name = file.getName(); // 三国演义_001_[评书网-今天很高兴,明天就IO了]_桃园三结义.avi
int index = name.indexOf("_");
String numberString = name.substring(index + 1, index + 4);
// System.out.println(numberString);
// int startIndex = name.lastIndexOf('_');
// int endIndex = name.lastIndexOf('.');
// String nameString = name.substring(startIndex + 1, endIndex);
// System.out.println(nameString);
int endIndex = name.lastIndexOf('_');
String nameString = name.substring(endIndex);
String newName = numberString.concat(nameString); // 001_桃园三结义.avi
// System.out.println(newName);
File newFile = new File(srcFolder, newName); // E:\\评书\\三国演义\\001_桃园三结义.avi
// 重命名即可
file.renameTo(newFile);
}
}
}
----------------------------------------------------------------
//递归:
* 有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问第二十个月的兔子对数为多少?
* 分析:我们要想办法找规律
* 兔子对数
* 第一个月: 1
* 第二个月: 1
* 第三个月: 2
* 第四个月: 3
* 第五个月: 5
* 第六个月: 8
* ...
*
* 由此可见兔子对象的数据是:
* 1,1,2,3,5,8...
* 规则:
* A:从第三项开始,每一项是前两项之和
* B:而且说明前两项是已知的
*
* 如何实现这个程序呢?
* A:数组实现
* B:变量的变化实现
* C:递归实现
*
* 假如相邻的两个月的兔子对数是a,b
* 第一个相邻的数据:a=1,b=1
* 第二个相邻的数据:a=1,b=2
* 第三个相邻的数据:a=2,b=3
* 第四个相邻的数据:a=3,b=5
* 看到了:下一次的a是以前的b,下一次是以前的a+b
public class DiGuiDemo2 {
public static void main(String[] args) {
// 定义一个数组
int[] arr = new int[20];
arr[0] = 1;
arr[1] = 1;
// arr[2] = arr[0] + arr[1];
// arr[3] = arr[1] + arr[2];
// ...
for (int x = 2; x < arr.length; x++) {
arr[x] = arr[x - 2] + arr[x - 1];
}
System.out.println(arr[19]);// 6765
System.out.println("----------------");
int a = 1;
int b = 1;
for (int x = 0; x < 18; x++) {
// 临时变量存储上一次的a
int temp = a;
a = b;
b = temp + b;
}
System.out.println(b);
System.out.println("----------------");
System.out.println(fib(20));
}
/*
* 方法: 返回值类型:int 参数列表:int n 出口条件: 第一个月是1,第二个月是1 规律: 从第三个月开始,每一个月是前两个月之和
*/
public static int fib(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return fib(n - 1) + fib(n - 2);
}
}
}
* 需求:请大家把E:\JavaSE目录下所有的java结尾的文件的绝对路径给输出在控制台。
*
* 分析:
* A:封装目录
* B:获取该目录下所有的文件或者文件夹的File数组
* C:遍历该File数组,得到每一个File对象
* D:判断该File对象是否是文件夹
* 是:回到B
* 否:继续判断是否以.java结尾
* 是:就输出该文件的绝对路径
* 否:不搭理它
public class FilePathDemo {
public static void main(String[] args) {
// 封装目录
File srcFolder = new File("E:\\JavaSE");
// 递归功能实现
getAllJavaFilePaths(srcFolder);
}
private static void getAllJavaFilePaths(File srcFolder) {
// 获取该目录下所有的文件或者文件夹的File数组
File[] fileArray = srcFolder.listFiles();
// 遍历该File数组,得到每一个File对象
for (File file : fileArray) {
// 判断该File对象是否是文件夹
if (file.isDirectory()) {
getAllJavaFilePaths(file);
} else {
// 继续判断是否以.java结尾
if (file.getName().endsWith(".java")) {
// 就输出该文件的绝对路径
System.out.println(file.getAbsolutePath());
}
}
}
}
}
-----------------2.0----------------------------------------------
输入流--读数据,输出流--写入数据
* IO流的分类:
* 流向:
* 输入流 读取数据
* 输出流 写出数据
* 数据类型:
* 字节流
* 字节输入流 读取数据 InputStream
* 字节输出流 写出数据 OutputStream
* 字符流
* 字符输入流 读取数据 Reader
* 字符输出流 写出数据 Writer
*
* 注意:一般我们在探讨IO流的时候,如果没有明确说明按哪种分类来说,默认情况下是按照数据类型来分的。
*
* 需求:我要往一个文本文件中输入一句话:"hello,io"
*
* 分析:
* A:这个操作最好是采用字符流来做,但是呢,字符流是在字节流之后才出现的,所以,今天我先讲解字节流如何操作。
* B:由于我是要往文件中写一句话,所以我们要采用字节输出流。
*
* 通过上面的分析后我们知道要使用:OutputStream
* 但是通过查看API,我们发现该流对象是一个抽象类,不能实例化。
* 所以,我们要找一个具体的子类。
* 而我们要找的子类是什么名字的呢?这个时候,很简单,我们回想一下,我们是不是要往文件中写东西。
* 文件是哪个单词:File
* 然后用的是字节输出流,联起来就是:FileOutputStream
* 注意:每种基类的子类都是以父类名作为后缀名。
* XxxOutputStream
* XxxInputStream
* XxxReader
* XxxWriter
* 查看FileOutputStream的构造方法:
* FileOutputStream(File file)
* FileOutputStream(String name)
*
* 字节输出流操作步骤:
* A:创建字节输出流对象
* B:写数据
* C:释放资源
public class FileOutputStreamDemo {
public static void main(String[] args) throws IOException {
// 创建字节输出流对象
// FileOutputStream(File file)
// File file = new File("fos.txt");
// FileOutputStream fos = new FileOutputStream(file);
// FileOutputStream(String name)
FileOutputStream fos = new FileOutputStream("fos.txt");
/*
* 创建字节输出流对象了做了几件事情:
* A:调用系统功能去创建文件
* B:创建fos对象
* C:把fos对象指向这个文件
*/
//写数据
fos.write("hello,IO".getBytes());
fos.write("java".getBytes());
//释放资源
//关闭此文件输出流并释放与此流有关的所有系统资源。
fos.close();
/*
* 为什么一定要close()呢?
* A:让流对象变成垃圾,这样就可以被垃圾回收器回收了
* B:通知系统去释放跟该文件相关的资源
*/
//java.io.IOException: Stream Closed
//fos.write("java".getBytes());
}
}
* 字节输入流操作步骤:
* A:创建字节输入流对象
* B:调用read()方法读取数据,并把数据显示在控制台
* C:释放资源
*
* 读取数据的方式:
* A:int read():一次读取一个字节
* B:int read(byte[] b):一次读取一个字节数组
int by=0;
while((by=fis.read()) !=-1){
System.out.print((char)by);
}
fis.close();
* 复制文本文件。
*
* 数据源:从哪里来
* a.txt -- 读取数据 -- FileInputStream
*
* 目的地:到哪里去
* b.txt -- 写数据 -- FileOutputStream
*
* java.io.FileNotFoundException: a.txt (系统找不到指定的文件。)
*
* 这一次复制中文没有出现任何问题,为什么呢?
* 上一次我们出现问题的原因在于我们每次获取到一个字节数据,就把该字节数据转换为了字符数据,然后输出到控制台。
* 而这一次呢?确实通过IO流读取数据,写到文本文件,你读取一个字节,我就写入一个字节,你没有做任何的转换。
* 它会自己做转换。
FileInputStream fis=new FileInputStream("fos.txt");
FileOutputStream fos=new FileOutputStream("b.txt");
int by=0;
while((by=fis.read()) != -1){
fos.write(by);
}
fis.close();
fos.close();
------------------------
// 数组的长度一般是1024或者1024的整数倍
byte[] bys = new byte[1024];
int len = 0;
while ((len = fis.read(bys)) != -1) {
System.out.print(new String(bys, 0, len));
}
// 释放资源
fis.close();
*将b.txt复制到c.txt
//封装数据源
FileReader fr=new FileReader("b.txt");
FileWriter fw=new FileWriter("c.txt");
char [] chs=new char[1024];
int len=0;
while((len=fr.read(chs)) != -1){
fw.write(chs,0,len);
}
fr.close();
fw.close();
* 字符流为了高效读写,也提供了对应的字符缓冲流。
* BufferedWriter:字符缓冲输出流
* BufferedReader:字符缓冲输入流
*
* BufferedWriter:字符缓冲输出流
* 将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。
* 可以指定缓冲区的大小,或者接受默认的大小。在大多数情况下,默认值就足够大了。
BufferedWriter bw=new BufferedWriter(new FileWriter("c.txt"));
bw.write("nihao");
bw.write("ma?");
bw.flush();
bw.close();
***读取c.txt的内容
BufferedReader bw=new BufferedReader(new FileReader("c.txt"));
char[] chs=new char[1024];
int len=0;
while((len=bw.read(chs)) != -1){
System.out.print(new String(chs, 0, len));
}
bw.close();
* 字符缓冲流的特殊方法:
* BufferedWriter:
* public void newLine():根据系统来决定换行符
* BufferedReader:
* public String readLine():一次读取一行数据
* 包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回 null
*吧c.txt复制到d.txt
BufferedReader br=new BufferedReader(new FileReader("c.txt"));
BufferedWriter bw=new BufferedWriter(new FileWriter("d.txt"));
String inne=null;
while((inne=br.readLine()) != null){
bw.write(inne);
bw.newLine();
bw.flush();
}
br.close();
bw.close();
* 需求:我有一个文本文件中存储了几个名称,请大家写一个程序实现随机获取一个人的名字。
*
* 分析:
* A:把文本文件中的数据存储到集合中
* B:随机产生一个索引
* C:根据该索引获取一个值
// 把文本文件中的数据存储到集合中
BufferedReader br = new BufferedReader(new FileReader("b.txt"));
ArrayList<String> array = new ArrayList<String>();
String line = null;
while ((line = br.readLine()) != null) {
array.add(line);
}
br.close();
// 随机产生一个索引
Random r = new Random();
int index = r.nextInt(array.size());
// 根据该索引获取一个值
String name = array.get(index);
System.out.println("该幸运者是:" + name);
* 需求:复制单极文件夹
*
* 数据源:e:\\demo
* 目的地:e:\\test
*
* 分析:
* A:封装目录
* B:获取该目录下的所有文本的File数组
* C:遍历该File数组,得到每一个File对象
* D:把该File进行复制
// 封装目录
File srcFolder = new File("e:\\demo");
// 封装目的地
File destFolder = new File("e:\\test");
// 如果目的地文件夹不存在,就创建
if (!destFolder.exists()) {
destFolder.mkdir();
}
// 获取该目录下的所有文本的File数组
File[] fileArray = srcFolder.listFiles();
// 遍历该File数组,得到每一个File对象
for (File file : fileArray) {
// System.out.println(file);
// 数据源:e:\\demo\\e.mp3
// 目的地:e:\\test\\e.mp3
String name = file.getName(); // e.mp3
File newFile = new File(destFolder, name); // e:\\test\\e.mp3
copyFile(file, newFile);
}
}
private static void copyFile(File file, File newFile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
file));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(newFile));
byte[] bys = new byte[1024];
int len = 0;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
bos.close();
bis.close();
}
* 需求:复制指定目录下的指定文件,并修改后缀名。
* 指定的文件是:.java文件。
* 指定的后缀名是:.jad
* 指定的目录是:jad
*
* 数据源:e:\\java\\A.java
* 目的地:e:\\jad\\A.jad
*
* 分析:
* A:封装目录
* B:获取该目录下的java文件的File数组
* C:遍历该File数组,得到每一个File对象
* D:把该File进行复制
* E:在目的地目录下改名
public class CopyFolderDemo {
public static void main(String[] args) throws IOException {
// 封装目录
File srcFolder = new File("e:\\java");
// 封装目的地
File destFolder = new File("e:\\jad");
// 如果目的地目录不存在,就创建
if (!destFolder.exists()) {
destFolder.mkdir();
}
// 获取该目录下的java文件的File数组
File[] fileArray = srcFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return new File(dir, name).isFile() && name.endsWith(".java");
}
});
// 遍历该File数组,得到每一个File对象
for (File file : fileArray) {
// System.out.println(file);
// 数据源:e:\java\DataTypeDemo.java
// 目的地:e:\\jad\DataTypeDemo.java
String name = file.getName();
File newFile = new File(destFolder, name);
copyFile(file, newFile);
}
// 在目的地目录下改名
File[] destFileArray = destFolder.listFiles();
for (File destFile : destFileArray) {
// System.out.println(destFile);
// e:\jad\DataTypeDemo.java
// e:\\jad\\DataTypeDemo.jad
String name =destFile.getName(); //DataTypeDemo.java
String newName = name.replace(".java", ".jad");//DataTypeDemo.jad
File newFile = new File(destFolder,newName);
destFile.renameTo(newFile);
}
}
private static void copyFile(File file, File newFile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
file));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(newFile));
byte[] bys = new byte[1024];
int len = 0;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
bos.close();
bis.close();
}
}
* 需求:复制多极文件夹
*
* 数据源:E:\JavaSE\day21\code\demos
* 目的地:E:\\
*
* 分析:
* A:封装数据源File
* B:封装目的地File
* C:判断该File是文件夹还是文件
* a:是文件夹
* 就在目的地目录下创建该文件夹
* 获取该File对象下的所有文件或者文件夹File对象
* 遍历得到每一个File对象
* 回到C
* b:是文件
* 就复制(字节流)
public class CopyFoldersDemo {
public static void main(String[] args) throws IOException {
// 封装数据源File
File srcFile = new File("E:\\JavaSE\\day21\\code\\demos");
// 封装目的地File
File destFile = new File("E:\\");
// 复制文件夹的功能
copyFolder(srcFile, destFile);
}
private static void copyFolder(File srcFile, File destFile)
throws IOException {
// 判断该File是文件夹还是文件
if (srcFile.isDirectory()) {
// 文件夹
File newFolder = new File(destFile, srcFile.getName());
newFolder.mkdir();
// 获取该File对象下的所有文件或者文件夹File对象
File[] fileArray = srcFile.listFiles();
for (File file : fileArray) {
copyFolder(file, newFolder);
}
} else {
// 文件
File newFile = new File(destFile, srcFile.getName());
copyFile(srcFile, newFile);
}
}
private static void copyFile(File srcFile, File newFile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
srcFile));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(newFile));
byte[] bys = new byte[1024];
int len = 0;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
bos.close();
bis.close();
}
}
------------------------------------
demo:
* 键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低存入文本文件
*
* 分析:
* A:创建学生类
* B:创建集合对象
* TreeSet<Student>
* C:键盘录入学生信息存储到集合
* D:遍历集合,把数据写到文本文件
*/
public class StudentDemo {
public static void main(String[] args) throws IOException {
// 创建集合对象
TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num = s2.getSum() - s1.getSum();
int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num;
int num3 = num2 == 0 ? s1.getMath() - s2.getMath() : num2;
int num4 = num3 == 0 ? s1.getEnglish() - s2.getEnglish() : num3;
int num5 = num4 == 0 ? s1.getName().compareTo(s2.getName())
: num4;
return num5;
}
});
// 键盘录入学生信息存储到集合
for (int x = 1; x <= 5; x++) {
Scanner sc = new Scanner(System.in);
System.out.println("请录入第" + x + "个的学习信息");
System.out.println("姓名:");
String name = sc.nextLine();
System.out.println("语文成绩:");
int chinese = sc.nextInt();
System.out.println("数学成绩:");
int math = sc.nextInt();
System.out.println("英语成绩:");
int english = sc.nextInt();
// 创建学生对象
Student s = new Student();
s.setName(name);
s.setChinese(chinese);
s.setMath(math);
s.setEnglish(english);
// 把学生信息添加到集合
ts.add(s);
}
// 遍历集合,把数据写到文本文件
BufferedWriter bw = new BufferedWriter(new FileWriter("students.txt"));
bw.write("学生信息如下:");
bw.newLine();
bw.flush();
bw.write("姓名,语文成绩,数学成绩,英语成绩");
bw.newLine();
bw.flush();
for (Student s : ts) {
StringBuilder sb = new StringBuilder();
sb.append(s.getName()).append(",").append(s.getChinese())
.append(",").append(s.getMath()).append(",")
.append(s.getEnglish());
bw.write(sb.toString());
bw.newLine();
bw.flush();
}
// 释放资源
bw.close();
System.out.println("学习信息存储完毕");
}
}
public class Student {
private String name;
private int chinese;
private int math;
private int english;
public int getSum() {
return this.chinese + this.math + this.english;
}
}
* 已知s.txt文件中有这样的一个字符串:“hcexfgijkamdnoqrzstuvwybpl”
* 请编写程序读取数据内容,把数据排序后写入ss.txt中。
*
* 分析:
* A:把s.txt这个文件给做出来
* B:读取该文件的内容,存储到一个字符串中
* C:把字符串转换为字符数组
* D:对字符数组进行排序
* E:把排序后的字符数组转换为字符串
* F:把字符串再次写入ss.txt中
// 读取该文件的内容,存储到一个字符串中
BufferedReader br = new BufferedReader(new FileReader("s.txt"));
String line = br.readLine();
br.close();
// 把字符串转换为字符数组
char[] chs = line.toCharArray();
// 对字符数组进行排序
Arrays.sort(chs);
// 把排序后的字符数组转换为字符串
String s = new String(chs);
// 把字符串再次写入ss.txt中
BufferedWriter bw = new BufferedWriter(new FileWriter("ss.txt"));
bw.write(s);
bw.newLine();
bw.flush();
bw.close();
* 用Reader模拟BufferedReader的readLine()功能
*
* readLine():一次读取一行,根据换行符判断是否结束,只返回内容,不返回换行符
public class MyBufferedReader {
private Reader r;
public MyBufferedReader(Reader r) {
this.r = r;
}
/*
* 思考:写一个方法,返回值是一个字符串。
*/
public String readLine() throws IOException {
/*
* 我要返回一个字符串,我该怎么办呢? 我们必须去看看r对象能够读取什么东西呢? 两个读取方法,一次读取一个字符或者一次读取一个字符数组
* 那么,我们要返回一个字符串,用哪个方法比较好呢? 我们很容易想到字符数组比较好,但是问题来了,就是这个数组的长度是多长呢?
* 根本就没有办法定义数组的长度,你定义多长都不合适。 所以,只能选择一次读取一个字符。
* 但是呢,这种方式的时候,我们再读取下一个字符的时候,上一个字符就丢失了 所以,我们又应该定义一个临时存储空间把读取过的字符给存储起来。
* 这个用谁比较和是呢?数组,集合,字符串缓冲区三个可供选择。
* 经过简单的分析,最终选择使用字符串缓冲区对象。并且使用的是StringBuilder
*/
StringBuilder sb = new StringBuilder();
// 做这个读取最麻烦的是判断结束,但是在结束之前应该是一直读取,直到-1
/*
hello
world
java
104101108108111
119111114108100
1069711897
*/
int ch = 0;
while ((ch = r.read()) != -1) { //104,101,108,108,111
if (ch == '\r') {
continue;
}
if (ch == '\n') {
return sb.toString(); //hello
} else {
sb.append((char)ch); //hello
}
}
// 为了防止数据丢失,判断sb的长度不能大于0
if (sb.length() > 0) {
return sb.toString();
}
return null;
}
/*
* 先写一个关闭方法
*/
public void close() throws IOException {
this.r.close();
}
}
* 测试MyBufferedReader的时候,你就把它当作BufferedReader一样的使用
public class MyBufferedReaderDemo {
public static void main(String[] args) throws IOException {
MyBufferedReader mbr = new MyBufferedReader(new FileReader("my.txt"));
String line = null;
while ((line = mbr.readLine()) != null) {
System.out.println(line);
}
mbr.close();
// System.out.println('\r' + 0); // 13
// System.out.println('\n' + 0);// 10
}
}
* 需求:DataStreamDemo.java复制到Copy.java中
* 数据源:
* DataStreamDemo.java -- 读取数据 -- FileReader -- BufferedReader
* 目的地:
* Copy.java -- 写出数据 -- FileWriter -- BufferedWriter -- PrintWriter
public class CopyFileDemo {
public static void main(String[] args) throws IOException {
// 以前的版本
// 封装数据源
// BufferedReader br = new BufferedReader(new FileReader(
// "DataStreamDemo.java"));
// // 封装目的地
// BufferedWriter bw = new BufferedWriter(new FileWriter("Copy.java"));
//
// String line = null;
// while ((line = br.readLine()) != null) {
// bw.write(line);
// bw.newLine();
// bw.flush();
// }
//
// bw.close();
// br.close();
// 打印流的改进版
// 封装数据源
BufferedReader br = new BufferedReader(new FileReader(
"DataStreamDemo.java"));
// 封装目的地
PrintWriter pw = new PrintWriter(new FileWriter("Copy.java"), true);
String line = null;
while((line=br.readLine())!=null){
pw.println(line);
}
pw.close();
br.close();
}
}
* 我有一个文本文件(user.txt),我知道数据是键值对形式的,但是不知道内容是什么。
* 请写一个程序判断是否有“lisi”这样的键存在,如果有就改变其实为”100”
*
* 分析:
* A:把文件中的数据加载到集合中
* B:遍历集合,获取得到每一个键
* C:判断键是否有为"lisi"的,如果有就修改
public class PropertiesTest {
public static void main(String[] args) throws IOException {
// 把文件中的数据加载到集合中
Properties prop = new Properties();
Reader r = new FileReader("user.txt");
prop.load(r);
r.close();
// 遍历集合,获取得到每一个键
Set<String> set = prop.stringPropertyNames();
for (String key : set) {
// 判断键是否有为"lisi"的,如果有就修改其值为"100"
if ("lisi".equals(key)) {
prop.setProperty(key, "100");
break;
}
}
// 把集合中的数据重新存储到文件中
Writer w = new FileWriter("user.txt");
prop.store(w, null);
w.close();
}
}