刘意 java基础视频_传智播客 2015年 刘意_Java基础视频-深入浅出精华版 笔记(day21~day23)(2016年4月8日13:28:21)...

15.复制文本文件的5种方式案例

复制文本文件

分析:

复制数据。假设我们知道用记事本打开并可以读懂,就用字符流。否则用字节流。

通过该原理,我们知道我们应该採用字符流更方便一些。

而字符流有5种方式。所以做这个题目我们有5种方式。推荐掌握第5种。

数据源:

c:\\a.txt -- FileReader -- BufferdReader

目的地:

d:\\b.txt -- FileWriter -- BufferedWriter

=======================================

public static void main(String[] args) throws IOException {

String srcString = "c:\\a.txt";

String destString = "d:\\b.txt";

// method1(srcString, destString);

// method2(srcString, destString);

// method3(srcString, destString);

// method4(srcString, destString);

method5(srcString, destString);

}

// 字符缓冲流一次读写一个字符串

private static void method5(String srcString, String destString)

throws IOException {

BufferedReader br = new BufferedReader(new FileReader(srcString));

BufferedWriter bw = new BufferedWriter(new FileWriter(destString));

String line = null;

while ((line = br.readLine()) != null) {

bw.write(line);

bw.newLine();

bw.flush();

}

bw.close();

br.close();

}

// 字符缓冲流一次读写一个字符数组

private static void method4(String srcString, String destString)

throws IOException {

BufferedReader br = new BufferedReader(new FileReader(srcString));

BufferedWriter bw = new BufferedWriter(new FileWriter(destString));

char[] chs = new char[1024];

int len = 0;

while ((len = br.read(chs)) != -1) {

bw.write(chs, 0, len);

}

bw.close();

br.close();

}

// 字符缓冲流一次读写一个字符

private static void method3(String srcString, String destString)

throws IOException {

BufferedReader br = new BufferedReader(new FileReader(srcString));

BufferedWriter bw = new BufferedWriter(new FileWriter(destString));

int ch = 0;

while ((ch = br.read()) != -1) {

bw.write(ch);

}

bw.close();

br.close();

}

// 基本字符流一次读写一个字符数组

private static void method2(String srcString, String destString)

throws IOException {

FileReader fr = new FileReader(srcString);

FileWriter fw = new FileWriter(destString);

char[] chs = new char[1024];

intlen = 0;

while ((len = fr.read(chs)) != -1) {

fw.write(chs, 0, len);

}

fw.close();

fr.close();

}

// 基本字符流一次读写一个字符

private static void method1(String srcString, String destString)

throws IOException {

FileReader fr = new FileReader(srcString);

FileWriter fw = new FileWriter(destString);

intch = 0;

while ((ch= fr.read()) != -1) {

fw.write(ch);

}

fw.close();

fr.close();

}

16.复制图片的4种方式案例

复制图片

分析:

复制数据。假设我们知道用记事本打开并可以读懂,就用字符流。否则用字节流。

通过该原理,我们知道我们应该採用字节流。

而字节流有4种方式。所以做这个题目我们有4种方式。

推荐掌握第4种。

数据源:

c:\\a.jpg -- FileInputStream -- BufferedInputStream

目的地:

d:\\b.jpg -- FileOutputStream -- BufferedOutputStream

==========================================

public static void main(String[] args) throws IOException {

// 使用字符串作为路径

// String srcString = "c:\\a.jpg";

// String destString = "d:\\b.jpg";

// 使用File对象做为參数

File srcFile = new File("c:\\a.jpg");

File destFile = new File("d:\\b.jpg");

// method1(srcFile, destFile);

// method2(srcFile, destFile);

// method3(srcFile, destFile);

method4(srcFile, destFile);

}

// 字节缓冲流一次读写一个字节数组

private static void method4(File srcFile, File destFile) throws IOException {

BufferedInputStream bis = new BufferedInputStream(new FileInputStream(

srcFile));

BufferedOutputStream bos = new BufferedOutputStream(

new FileOutputStream(destFile));

byte[] bys = new byte[1024];

int len = 0;

while ((len = bis.read(bys)) != -1) {

bos.write(bys, 0, len);

}

bos.close();

bis.close();

}

// 字节缓冲流一次读写一个字节

private static void method3(File srcFile, File destFile) throws IOException {

BufferedInputStream bis = new BufferedInputStream(new FileInputStream(

srcFile));

BufferedOutputStream bos = new BufferedOutputStream(

new FileOutputStream(destFile));

int by = 0;

while ((by = bis.read()) != -1) {

bos.write(by);

}

bos.close();

bis.close();

}

// 基本字节流一次读写一个字节数组

private static void method2(File srcFile, File destFile) throws IOException {

FileInputStream fis = new FileInputStream(srcFile);

FileOutputStream fos = new FileOutputStream(destFile);

byte[] bys = new byte[1024];

int len = 0;

while ((len = fis.read(bys)) != -1) {

fos.write(bys, 0, len);

}

fos.close();

fis.close();

}

// 基本字节流一次读写一个字节

private static void method1(File srcFile, File destFile) throws IOException {

FileInputStream fis = new FileInputStream(srcFile);

FileOutputStream fos = new FileOutputStream(destFile);

int by = 0;

while ((by = fis.read()) != -1) {

fos.write(by);

}

fos.close();

fis.close();

}

==============================================

17.把集合中的数据存储到文本文件案例 ArrayListToFile

需求:把ArrayList集合中的字符串数据存储到文本文件

分析:

通过题目的意思我们能够知道例如以下的一些内容。

ArrayList集合里存储的是字符串。

遍历ArrayList集合,把数据获取到。

然后存储到文本文件里。

文本文件说明使用字符流。

数据源:

ArrayList -- 遍历得到每个字符串数据

目的地:

a.txt -- FileWriter -- BufferedWriter

=================================================

public static void main(String[] args) throws IOException {

// 封装数据与(创建集合对象)

ArrayList array = new ArrayList();

array.add("hello");

array.add("world");

array.add("java");

// 封装目的地

BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));

// 遍历集合

for (String s : array) {

// 写数据

bw.write(s);

bw.newLine();

bw.flush();

}

// 释放资源

bw.close();

}

======================================

18.把文本文件里的数据存储到集合中案例  FileToArrayList

需求:从文本文件里读取数据(每一行为一个字符串数据)到集合中。并遍历集合

*

* 分析:

*         通过题目的意思我们能够知道例如以下的一些内容,

*             数据源是一个文本文件。

*             目的地是一个集合。

*             并且元素是字符串。

*

* 数据源:

*         b.txt -- FileReader -- BufferedReader

* 目的地:

*         ArrayList

======================================

public static void main(String[] args) throws IOException {

// 封装数据源

BufferedReader br = new BufferedReader(new FileReader("b.txt"));

// 封装目的地(创建集合对象)

ArrayList array = new ArrayList();

// 读取数据存储到集合中

String line = null;

while ((line = br.readLine()) != null) {

array.add(line);

}

// 释放资源

br.close();//别忘记这一步

// 遍历集合

for (String s : array) {

System.out.println(s);

}

}

===========================================

19.随机获取文本文件里的姓名案例

需求:我有一个文本文件里存储了几个名称。请大家写一个程序实现随机获取一个人的名字。

分析:

A:把文本文件里的数据存储到集合中

B:随机产生一个索引

C:依据该索引获取一个值

public static void main(String[] args) throws IOException {

// 把文本文件里的数据存储到集合中

BufferedReader br = new BufferedReader(new FileReader("b.txt"));

ArrayList array = new ArrayList();

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);

}

==========================================

20.复制单级目录案例

/*

* 需求:复制单极目录

*

* 数据源:e:\\demo

* 目的地:e:\\test

*

* 分析:

*         A:封装文件夹

*         B:获取该文件夹下的全部文本的File数组

*         C:遍历该File数组。得到每个File对象

*         D:把该File进行复制

*/

public class CopyFolderDemo {

public static void main(String[] args) throws IOException {

// 封装文件夹

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();

}

}

=====================================================

注意:文件不存在能够自己主动创建。可是目录不存在不会自己主动创建,因此

if (!destFolder.exists()) {

destFolder.mkdir();

}

21.复制指定文件夹下指定后缀名的文件并改动名称案例

数据源

c2c68f1429500d059a4e1560bb58086d.png

/*

* 需求:复制指定文件夹下的指定文件。并改动后缀名。

* 指定的文件是:.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();

}

}

a912dfe13c1c88392551c4f8d2177898.png

4263caeb5fc2e1c40a83ef37fff8d536.png

==================================

执行后演示样例

f7fc7af92d89d8ec70b5331373dd7a65.png

而本人先前自己模仿了一个。功能稍微不一样

数据源

e1e064fc602f6894807a3b4a7b705ca5.png

/*

* 需求:复制指定文件夹下的指定文件,并改动后缀名

* 这个文件是我本人做的,问题是:目录复制没处理好(copyDirectory方法略繁琐 )

*

* 数据源:g:\\java\\A.java

*  目的地:f:\\jad\\A.jad

*/

public class CopyFolderDemo2 {

public static void main(String[] args) throws IOException {

// 封装文件夹

File srcFolder = new File("g:\\java");

File desFolder = new File("f:\\jad");

if (!desFolder.exists()) {

desFolder.mkdir();

}

File[] files = srcFolder.listFiles();

for (File f : files) {

if (!f.isDirectory()) {

String name = f.getName();

File newFile = new File(desFolder, name);

copyFile(f, newFile);

modifyFile(desFolder);

} else {

String folderName = f.getName();

String desFolderName = desFolder.getName();

copyDirectory(desFolder, folderName);

}

}

}

private static void copyDirectory(File desFolder, String folderName) {

File newFolder = new File(desFolder, folderName);

newFolder.mkdirs();

}

private static void modifyFile(File desFolder) {

File[] files = desFolder.listFiles();

for (File f : files) {

if (!f.isDirectory()) {

String name = f.getName();

if (name.endsWith(".java")) {

int index = name.indexOf(".");

String fileNameString = name.substring(0, index);

String newNameString = fileNameString.concat(".jad");

File newFile = new File(desFolder, newNameString);

f.renameTo(newFile);

}

}

}

}

private static void copyFile(File f, File newFile) throws IOException {

BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));

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);

}

bis.close();

bos.close();

}

}

执行演示样例

e2f808987b08895cd4950ece3fea8adc.png

22.复制多级目录案例

/*

* 需求:复制多极目录

*

* 数据源: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();

}

}

23.键盘录入学生信息依照总分排序并写入文本文件案例

Student类例如以下

===================

public class Student {

// 姓名

private String name;

// 语文成绩

private int chinese;

// 数学成绩

private int math;

// 英语成绩

private int english;

public Student() {

super();

}

public Student(String name, int chinese, int math, int english) {

super();

this.name = name;

this.chinese = chinese;

this.math = math;

this.english = english;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getChinese() {

return chinese;

}

public void setChinese(int chinese) {

this.chinese = chinese;

}

public int getMath() {

return math;

}

public void setMath(int math) {

this.math = math;

}

public int getEnglish() {

return english;

}

public void setEnglish(int english) {

this.english = english;

}

public int getSum() {

return this.chinese + this.math + this.english;

}

}

==========================================

測试类

=====

public class StudentDemo {

public static void main(String[] args) throws IOException {

// 创建集合对象

TreeSet ts = new TreeSet(new Comparator() {

@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) {

StringBuildersb = 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("学习信息存储完成");

}

}

24.把一个文件里的字符串排序后再写入还有一个文件案例

已知s.txt文件里有这种一个字符串:“hcexfgijkamdnoqrzstuvwybpl”

请编敲代码读取数据内容,把数据排序后写入ss.txt中。

分析:

A:把s.txt这个文件给做出来

B:读取该文件的内容。存储到一个字符串中

C:把字符串转换为字符数组

D:对字符数组进行排序

E:把排序后的字符数组转换为字符串

F:把字符串再次写入ss.txt中

public static void main(String[] args) throws IOException {

// 读取该文件的内容,存储到一个字符串中

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();

}

//注意一下readLine(无需flush) 和 newLine,还有字符数组转换为字符串

25.自己定义类模拟BufferedReader的readLine()功能案例(有一定难度)

先写MyBufferedReader类

================================================================

/*

* 用Reader模拟BufferedReader的readLine()功能

*

* readLine():一次读取一行,依据换行符推断是否结束,仅仅返回内容,不返回换行符

*/

public class MyBufferedReader {

private Reader r;

public MyBufferedReader(Reader r) {

this.r = r;

}

/*

* 思考:写一个方法,返回值是一个字符串。

*/

public String readLine() throws IOException {

/*

* 我要返回一个字符串,我该怎么办呢?

我们必须去看看r对象可以读取什么东西呢? 两个读取方法,一次读取一个字符或者一次读取一个字符数组

* 那么。我们要返回一个字符串。用哪个方法比較好呢? 我们非常easy想到字符数组比較好,可是问题来了。就是这个数组的长度是多长呢?

* 根本就没有办法定义数组的长度,你定义多长都不合适。 所以,仅仅能选择一次读取一个字符。

* 可是呢。这样的方式的时候。我们再读取下一个字符的时候,上一个字符就丢失了 所以,我们又应该定义一个暂时存储空间把读取过的字符给存储起来。

* 这个用谁比較和是呢?数组。集合,字符串缓冲区三个可供选择。

* 经过简单的分析。终于选择使用字符串缓冲区对象。而且使用的是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;//必须\r\n同一时候存在的时候才算换行,因此这里继续

}

if (ch == '\n') {

return sb.toString(); //hello

} else {

sb.append((char)ch); //hello//必须转换。不然就会104,101,108,108,111

}

}

// 为了防止数据丢失,推断sb的长度不能大于0//反正就是不管怎样,仅仅要有数据了。最后都来拼一下反正数据丢失

if (sb.length() > 0) {

return sb.toString();

}

return null;

}

/*

* 先写一个关闭方法

*/

public void close() throws IOException {

this.r.close();//表面上调用Buffered……的方法。实际上还是用r自身的close方法

}

}

============================================================

a851b6a199b4e57838bcf48041d5ca0e.png

可是的话,。

489757a8519d1e247b7c0fb41d757e72.png

以下是測试类

===========================================

/*

* 測试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//通过加0的方法能够查看字符相应的数字编码

// System.out.println('\n' + 0);// 10

}

}

==============================

26.LineNumberReader的使用案例

5c4b8571b1c95258f8c7966201acae5a.png

由上图可知。其父类是BufferedReader

BufferedReader

|--LineNumberReader

public int getLineNumber()获得当前行号。

public void setLineNumber(int lineNumber)

public static void main(String[] args) throws IOException {

LineNumberReader lnr = new LineNumberReader(new FileReader("my.txt"));

// 从10開始才比較好

// lnr.setLineNumber(10);

// System.out.println(lnr.getLineNumber());

// System.out.println(lnr.getLineNumber());

// System.out.println(lnr.getLineNumber());

String line = null;

while ((line = lnr.readLine()) != null) {

System.out.println(lnr.getLineNumber() + ":" + line);

}

lnr.close();

}

默认

611cc844cc47c715b3a8263aa2056108.png

set之后

552b2a55f7c84d7b31b99f3e57c72c28.png

(自己定义类模拟LineNumberReader的获取行号功能案例省略==)

day21笔记补充

IO流小结(掌握)

IO流

|--字节流

|--字节输入流

InputStream

int read():一次读取一个字节

int read(byte[] bys):一次读取一个字节数组

|--FileInputStream

|--BufferedInputStream

|--字节输出流

OutputStream

void write(int by):一次写一个字节

void write(byte[] bys,int index,int len):一次写一个字节数组的一部分

|--FileOutputStream

|--BufferedOutputStream

|--字符流

|--字符输入流

Reader

int read():一次读取一个字符

int read(char[] chs):一次读取一个字符数组

|--InputStreamReader

|--FileReader

|--BufferedReader

String readLine():一次读取一个字符串

|--字符输出流

Writer

void write(int ch):一次写一个字符

void write(char[] chs,int index,int len):一次写一个字符数组的一部分

|--OutputStreamWriter

|--FileWriter

|--BufferedWriter

void newLine():写一个换行符

void write(String line):一次写一个字符串

今天写过的案例(理解 练习一遍)

A:复制文本文件 5种方式(掌握)

B:复制图片(二进制流数据) 4种方式(掌握)

C:把集合中的数据存储到文本文件

D:把文本文件里的数据读取到集合并遍历集合

E:复制单级目录

F:复制单级目录中指定的文件并改动名称

回想一下批量改动名称

G:复制多级目录

H:键盘录入学生信息依照总分从高到低存储到文本文件

I:把某个文件里的字符串排序后输出到还有一个文本文件里

J:用Reader模拟BufferedReader的特有功能

K:模拟LineNumberReader的特有功能

day22

1.登录注冊案例IO版实现

简要给代码,详细自己排错。敲。

与集合的注冊案例想比,UserDaoImpl不一样,其余的都一样。

=========================================

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import cn.itcast.dao.UserDao;

import cn.itcast.pojo.User;

/**

* 这是用户操作的详细实现类(IO版)

*

* @author 风清扬

* @version V1.1

*

*/

public class UserDaoImpl implements UserDao {

// 为了保证文件一载入就创建,在这里以下的红色部分使用了static静态代码块,类一载入就运行并且仅仅运行一次

private staticFile file = new File("user.txt");

static {

try {

file.createNewFile();

} catch (IOException e) {

System.out.println("创建文件失败");

// e.printStackTrace();

}

}

@Override

public boolean isLogin(String username, String password) {

boolean flag= false;

BufferedReader br = null;

try {

// br = new BufferedReader(new FileReader("user.txt"));

br = new BufferedReader(new FileReader(file));

String line = null;

while ((line = br.readLine()) != null) {

// username=password

String[] datas = line.split("=");//利用了字符串的方法。利用正則表達式拆分字符串

if (datas[0].equals(username) && datas[1].equals(password)) {

flag = true;

break;

}

}

} catch (FileNotFoundException e) {//本类全部的异常仅仅能try……catch处理,由于抛(throws)的话会比較麻烦并且影响其他的类。违背了独立改动且不影响其他类的初衷

System.out.println("用户登录找不到信息所在的文件");

// e.printStackTrace();

} catch (IOException e) {

System.out.println("用户登录失败");

// e.printStackTrace();

} finally {

if (br != null) {

try {

br.close();

} catch (IOException e) {

System.out.println("用户登录释放资源失败");

// e.printStackTrace();

}

}

}

return flag;

}

@Override

public void regist(User user) {

/*

* 为了让注冊的数据可以有一定的规则,我就自定义了一个规则: username=password

*/

BufferedWriter bw = null;

try {

// bw = new BufferedWriter(new FileWriter("user.txt"));

// bw = new BufferedWriter(new FileWriter(file));

// 为了保证数据是追加写入,必须加true

bw = new BufferedWriter(new FileWriter(file, true));//不加true的话。又一次创建文件会造成上一次的注冊信息丢失

bw.write(user.getUsername() + "=" + user.getPassword());

bw.newLine();

bw.flush();

} catch (IOException e) {

System.out.println("用户注冊失败");

// e.printStackTrace();

} finally {

if (bw != null) {

try {

bw.close();

} catch (IOException e) {

System.out.println("用户注冊释放资源失败");

// e.printStackTrace();

}

}

}

}

}

附:String的split方法以及user.txt里面保存的信息

68d368f471b0c537fb8cd426a81e16a7.png

注冊信息保存在文件里。不会丢失。

0299d2788af421c2f06c243a9667c476.png

2.数据输入输出流

bdad5903c6cd3ac8e6acbd2d22b1a5bf.png

能够读写基本数据类型的数据

数据输入流:DataInputStream

DataInputStream(InputStreamin)

数据输出流:DataOutputStream

DataOutputStream(OutputStreamout)

===================================

public static void main(String[] args) throws IOException {

// 写

// write();

// 读

read();

}

private static void read() throws IOException {

// DataInputStream(InputStream in)

// 创建数据输入流对象

DataInputStream dis = new DataInputStream(

new FileInputStream("dos.txt"));

// 读数据

byte b = dis.readByte();

short s = dis.readShort();

int i = dis.readInt();

long l = dis.readLong();

float f = dis.readFloat();

double d = dis.readDouble();

char c = dis.readChar();

boolean bb = dis.readBoolean();

// 释放资源

dis.close();

System.out.println(b);

System.out.println(s);

System.out.println(i);

System.out.println(l);

System.out.println(f);

System.out.println(d);

System.out.println(c);

System.out.println(bb);

}

private static void write() throws IOException {

// DataOutputStream(OutputStream out)

// 创建数据输出流对象

DataOutputStream dos = new DataOutputStream(new FileOutputStream(

"dos.txt"));

// 写数据了

dos.writeByte(10);

dos.writeShort(100);

dos.writeInt(1000);

dos.writeLong(10000);

dos.writeFloat(12.34F);//有一个类型转换

dos.writeDouble(12.56);

dos.writeChar('a');

dos.writeBoolean(true);

// 释放资源

dos.close();

}

==========================================

注意一个问题,假设仅仅有DataOutputStream来写文件。直接双击打开文件。读到的数据是乱码

7ac8150e2e504a6d2b4cdb969616c2db.png

3.内存操作流的概述和解说

内存操作流:用于处理暂时存储信息的。程序结束,数据就从内存中消失。

字节数组:

ByteArrayInputStream

ByteArrayOutputStream

字符数组:

CharArrayReader

CharArrayWriter

字符串:

StringReader

StringWriter

7c5a94ec0512ce681a7bb309d6b6c522.png

对于ByteArrayOutputStream:

此类实现了一个输出流,当中的数据被写入一个 byte 数组。缓冲区会随着数据的不断写入而自己主动增长。可使用toByteArray() 和 toString() 获取数据。

关闭 ByteArrayOutputStream 无效。此类中的方法在关闭此流后仍可被调用,而不会产生不论什么 IOException。(说白了就是不用close方法了)

对于ByteArrayInputStream :

ByteArrayInputStream 包括一个内部缓冲区,该缓冲区包括从流中读取的字节。

内部计数器跟踪 read 方法要提供的下一个字节。

关闭 ByteArrayInputStream 无效。

此类中的方法在关闭此流后仍可被调用。而不会产生不论什么 IOException。

bc69d1cf1eba67ff0039310b20d8a9eb.png

public static void main(String[] args) throws IOException {

// 写数据

// ByteArrayOutputStream()

ByteArrayOutputStream baos = new ByteArrayOutputStream();

// 写数据

for (int x = 0; x 

baos.write(("hello" + x).getBytes());

}

// 释放资源

//通过查看源代码我们知道这里什么都没做,所以根本须要close()

// baos.close();

// public byte[] toByteArray()

byte[] bys = baos.toByteArray();

// 读数据

// ByteArrayInputStream(byte[] buf)

ByteArrayInputStream bais = new ByteArrayInputStream(bys);

int by = 0;

while ((by = bais.read()) != -1) {

System.out.print((char) by);

}

// bais.close();//不须要close

}

4.打印流的概述和特点

打印流

字节流打印流    PrintStream

字符打印流    PrintWriter

打印流的特点:

A:仅仅有写数据的。没有读取数据。

仅仅能操作目的地,不能操作数据源。

B:能够操作随意类型的数据。

C:假设启动了自己主动刷新,可以自己主动刷新。(假设不启动的话。不刷新文件(就是flush或者close)里面是没有数据的)

D:该流是能够直接操作文本文件的。

哪些流对象是能够直接操作文本文件的呢?

FileInputStream

FileOutputStream

FileReader

FileWriter

PrintStream

PrintWriter

看API,查流对象的构造方法,假设同一时候有File类型和String类型的參数,一般来说就是能够直接操作文件的。

流:

基本流:就是可以直接读写文件的

高级流:在基本流基础上提供了一些其它的功能

2cb447f3a9249c8267140be11f88d74a.png

==========================================

public static void main(String[] args) throws IOException {

// 作为Writer的子类使用

PrintWriter pw = new PrintWriter("pw.txt");

pw.write("hello");

pw.write("world");

pw.write("java");

pw.close();//没有这句话不出数据,由于这不是自己主动刷新的(或者)

}

5.PrintWriter实现自己主动刷新和换行

能够操作随意类型的数据。

print()

println()

public static void main(String[] args) throws IOException {

PrintWriter pw = new PrintWriter("pw2.txt");

pw.print("hello");//print方法可接受随意类型的数据

pw.print(100);

pw.print(true);

pw.close();

}

但以上的方法并没有实现自己主动刷新

要实现自己主动刷新的话,

ac68a1d36b82443d5faf5b818fd75865.png

启动自己主动刷新

PrintWriter pw = new PrintWriter(new FileWriter("pw2.txt"), true);//要设置true

还是应该调用println()的方法才干够(调用print自己主动刷新不了)

这个时候不只自己主动刷新了,还实现了数据的换行。

public static void main(String[] args) throws IOException {

// 创建打印流对象

// PrintWriter pw = new PrintWriter("pw2.txt");

PrintWriter pw = new PrintWriter(new FileWriter("pw2.txt"), true);

// write()是搞不定的。怎么办呢?

// 我们就应该看看它的新方法

// pw.print(true);

// pw.print(100);

// pw.print("hello");

pw.println("hello");

pw.println(true);

pw.println(100);

pw.close();

}

注意:println()

事实上等价于于:

bw.write();

bw.newLine();

bw.flush();

一句顶三句

6.打印流改进复制文本文件案例

需求:DataStreamDemo.java拷贝到Copy.java中

数据源:

DataStreamDemo.java -- 读取数据 -- FileReader -- BufferedReader

目的地:

Copy.java -- 写出数据 -- FileWriter -- BufferedWriter -- PrintWriter

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();

}

===============================================

public static void main(String[] args) {

// 打印流的改进版

// 封装数据源

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();

}

=============================================

7.标准输入输出流概述和输出语句的本质------System.out

50edcc551ecf4b7f005e0d24ca03d88a.png

标准输入输出流

System类中的两个成员变量:

public staticfinal InputStream in “标准”输入流。

public staticfinal PrintStream out “标准”输出流。

InputStream is = System.in;

PrintStream ps = System.out;

f14e8f364961484ca2d4d851594775c2.png

public static void main(String[] args) {

// 有这里的解说我们就知道了,这个输出语句其本质是IO流操作,把数据输出到控制台。

System.out.println("helloworld");

// 获取标准输出流对象

PrintStream ps = System.out;

ps.println("helloworld");

ps.println();

// ps.print();//这种方法不存在

// System.out.println();

// System.out.print();

}

8.标准输入输出流概述和输出语句的本质------System.in

public static void main(String[] args) throws IOException {

//获取标准输入流

InputStream is = System.in;

//我要一次获取一行行不行呢?

//行。

//怎么实现呢?

//要想实现。首先你得知道一次读取一行数据的方法是哪个呢?

//readLine()

//而这种方法在哪个类中呢?

//BufferedReader

//所以。你这次应该创建BufferedReader的对象,可是底层还是的使用标准输入流

// BufferedReader br = new BufferedReader(is);

//依照我们的推想,如今应该能够了,可是却报错了

//原因是:字符缓冲流仅仅能针对字符流操作,而你如今是字节流。所以不能是用?

//那么。我还就想使用了,请大家给我一个解决方式?

//把字节流转换为字符流,然后在通过字符缓冲流操作

// InputStreamReader isr = new InputStreamReader(is);

// BufferedReader br= new BufferedReader(isr);

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

//注意这里的字节流转换成字符流。利用了InputStreamReader转换流

System.out.println("请输入一个字符串:");

String line = br.readLine();

System.out.println("你输入的字符串是:" + line);

System.out.println("请输入一个整数:");

// int i = Integer.parseInt(br.readLine());

line = br.readLine();

int i = Integer.parseInt(line);

System.out.println("你输入的整数是:" + i);

}

//利用上述代码模仿了Scanner的键盘录入功能

注意下面方法

6051775729e71339d37137b4e6d2a2c9.png

9.输出语句用字符缓冲流改进

public static void main(String[] args) throws IOException {

// 获取标准输入流

// // PrintStream ps = System.out;

// // OutputStream os = ps;//这个就是多态

//上面两句简化为一句----OutputStream os = System.out; // 多态

// // 我能不能依照刚才使用标准输入流的方式一样把数据输出到控制台呢?

// OutputStreamWriter osw = new OutputStreamWriter(os);

// BufferedWriter bw = new BufferedWriter(osw);

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(

System.out));//合并为一句

bw.write("hello");

bw.newLine();

// bw.flush();

bw.write("world");

bw.newLine();

// bw.flush();

bw.write("java");

bw.newLine();

bw.flush();

bw.close();

}

10.随机訪问流概述和写出数据

随机訪问流:

RandomAccessFile类不属于流,是Object类的子类。

但它融合了InputStream和OutputStream的功能。

支持对文件的随机訪问读取和写入。

public RandomAccessFile(String name,String mode):第一个參数是文件路径。第二个參数是操作文件的模式。

模式有四种,我们最经常使用的一种叫"rw",这样的方式表示我既能够写数据,也能够读取数据

cc39a962a722185b0f989869940e32bb.png

这个RandomAccessFile类还能够读和写

3832f8cb27f43d766b03bc62bb131fe5.png

11.随机訪问流读取数据和操作文件指针

===========================================

public static void main(String[] args) throws IOException {

read();

}

private static void read() throws IOException {

// 创建随机訪问流对象

RandomAccessFile raf = new RandomAccessFile("raf.txt", "rw");

int i = raf.readInt();

System.out.println(i);

// 该文件指针能够通过 getFilePointer方法读取。并通过 seek 方法设置。

System.out.println("当前文件的指针位置是:" + raf.getFilePointer());//4

char ch = raf.readChar();

System.out.println(ch);

System.out.println("当前文件的指针位置是:" + raf.getFilePointer());//6

String s = raf.readUTF();

System.out.println(s);

System.out.println("当前文件的指针位置是:" + raf.getFilePointer());//14(本来是12的。多出来两个字节的原因能够看API,事实上是识别UTF编码的两个字节)

// 我不想重头開始了,我就要读取a,怎么办呢?

raf.seek(4);//从0開始计算

ch = raf.readChar();

System.out.println(ch);

}

======================================================

输出演示样例

97bd0ab47e2f05891f085625e4987b78.png

12.合并流读取两个文件的内容拷贝到一个文件里

合并流就是按顺序读取两个文件然后合并到一个新的文件里

38a9415c2f19e6e82ec819d6f3812581.png

public static void main(String[] args) throws IOException {

InputStream is1= new FileInputStream("pw.txt");

InputStream is2= new FileInputStream("pw2.txt");

// SequenceInputStream(InputStream s1, InputStream s2)

SequenceInputStream sis = new SequenceInputStream(is1, is2);

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.txt"));

// 怎样写读写呢。事实上非常easy。你就依照曾经怎么读写,如今还是怎么读写

byte[] bys = new byte[1024];

int len = 0;

while ((len = sis.read(bys)) != -1) {

bos.write(bys, 0, len);

}

sis.close();

bos.close();

=============================================

执行演示样例

执行前

eb8271fad142bec2124d0eb6cc152854.png

2f90a37f1698d1e10a891ab337406870.png

执行后

638c6f9fb5e2c77068f333789c09e09b.png

13.合并流读取多个文件的内容拷贝到一个文件里

public static void main(String[] args) throws IOException {

// 需求:把以下的三个文件的内容拷贝到pwsum.txt中

// SequenceInputStream(Enumeration e)

// 通过简单的回想我们知道了Enumeration是Vector中的一个方法的返回值类型。

// Enumeration elements()

Vector v = new Vector();

InputStream is1 = new FileInputStream("pw.txt");

InputStream is2 = new FileInputStream("pw2.txt");

InputStream is3 = new FileInputStream("pw3.txt");

v.add(is1);

v.add(is2);

v.add(is3);

Enumeration e = v.elements();

SequenceInputStream sis = new SequenceInputStream(e);//接收一个參数

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("pwsum.txt"));

byte[] bys = new byte[1024];

int len = 0;

while ((len = sis.read(bys)) != -1) {

bos.write(bys, 0, len);

}

sis.close();

bos.close();

}

14.序列化流和反序列化流的概述和使用

序列化流   ObjectOutputStream

反序列化流  ObjectInputStream

序列化流:把对象依照流一样的方式存入文本文件或者在网络中传输。对象 -- 流数据(ObjectOutputStream)

反序列化流:把文本文件里的流对象数据或者网络中的流对象数据还原成对象。

流数据 -- 对象(ObjectInputStream)

首先。写序列化流Demo的write方法。

public static void main(String[] args) throws IOException,

ClassNotFoundException {

// 因为我们要对对象进行序列化,所以我们先自己定义一个类

// 序列化数据事实上就是把对象写到文本文件

write();

}

private static void write() throws IOException{

// 创建序列化流对象

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(

"oos.txt"));

// 创建对象

Person p = new Person("林青霞", 27);

// public final void writeObject(Object obj)

oos.writeObject(p);

// 释放资源

oos.close();

}

======================================================

然后,创建一个Person类

import java.io.Serializable;

public class Personimplements Serializable {

private String name;

private int age;

public Person() {

super();

}

public Person(String name, int age) {

super();

this.name = name;

this.age = age;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

@Override

public String toString() {

return "Person [name=" + name + ", age=" + age + "]";

}

}

============================

要说明的是。在Person类还没实现 Serializable 这个接口的时候。执行会有异常

NotSerializableException:未序列化异常

51dbcbf8627bfea958058cedfde79e51.png

查API

11901fe0f68495313cd12683b2a96111.png

因此,要想没报错,必须在Person类中实现 Serializable 这个接口

可是:你会发现。没有重写不论什么方法啊!!。

没错,由于,本来就不用重写不论什么的方法!

解析例如以下:

类通过实现 java.io.Serializable 接口以启用其序列化功能。

未实现此接口的类将无法使其不论什么状态序列化或反序列化。

该接口竟然没有不论什么方法,类似于这样的没有方法的接口被称为标记接口。

然后。再次执行没报错后,直接打开文件是看不懂的

b93cc6aae3b4194d6f1d39c12c95d797.png

序列化的流必需要反序列的流"解锁"才干够啊

最后。增加反序列流的代码例如以下

66f7055caf57736df28c40f39a62fe9a.png

执行(不报错了)toString方法在Person类中已经重写

注意这一步

// 还原对象

Object obj = ois.readObject();

obj尽管是Object类型,可是事实上是Person对象

385d1ecd3b9f08d51c3c75dfa30f1023.png

可是。另一个小问题

怎样解决序列化时候的黄色警告线问题

921b1761e6d642e4c9f50a1cde9f676c.png

当Person类进行了修改的时候(比方private int age 改为 int age)把代码保存再次执行(仅仅执行读操作而不进行第二次写入)会报错产生异常

d2aff13f67f857ead77fd1b622834556.png

产生的原因:

为什么会有问题呢?

Person类实现了序列化接口。那么它本身也应该有一个标记值。

这个标记值如果是100。

開始的时候:

Person.class -- id=100

wirte数据: oos.txt -- id=100

read数据: oos.txt -- id=100

如今:

Person.class -- id=200

wirte数据: oos.txt -- id=100

read数据: oos.txt -- id=100

解决问题的办法:

我们在实际开发中。可能还须要使用曾经写过的数据,不能又一次写入。

怎么办呢?

回忆一下原因是由于它们的id值不匹配。

每次改动java文件的内容的时候,class文件的id值都会发生改变。

而读取文件的时候。会和class文件里的id值进行匹配。所以。就会出问题。

可是呢,假设我有办法。让这个id值在java文件里是一个固定的值,这样,你改动文件的时候。这个id值还会发生改变吗?

不会。

如今的关键是我怎样可以知道这个id值怎样表示的呢?

不用操心。你不用记住,也没关系,点击鼠标就可以。

你难道没有看到黄色警告线吗?

c4c4da0d4a45228608997fd62a538818.png

在Person类中加一下语句

private static final long serialVersionUID = -2071565876962058344L;

abb50875c8b5d6d847f63557d2533e6e.png

另一个要注意的问题:

注意:

我一个类中可能有非常多的成员变量,有些我不想进行序列化。请问该怎么办呢?

使用transientkeyword声明不须要序列化的成员变量

也就是用transientkeyword

372bf1404ef19b0085c17961ea0156db.png

把private int age改动为

private transientint age;

然后执行会发现age的值为0了,也就是说,age的值将不被记住是27了

d137ddd460e05e460d94488d82a7d7db.png

15.Properties的概述和作为Map集合的使用(注意:Properties并没有泛型)

Properties:属性集合类。是一个能够和IO流相结合使用的集合类。

Properties 可保存在流中或从流中载入。

属性列表中每一个键及其相应值都是一个字符串。

是Hashtable的子类。说明是一个Map集合。

public static void main(String[] args) {

// 作为Map集合的使用

// 以下这样的使用方法是错误的,一定要看API,假设没有<>,就说明该类不是一个泛型类,在使用的时候就不能加泛型

// Properties prop = new Properties();

Properties prop = new Properties();

// 加入元素

prop.put("it002", "hello");

prop.put("it001", "world");

prop.put("it003", "java");

// System.out.println("prop:" + prop);

// 遍历集合,注意红字是Object而不是String,由于上面的put方法本来就是接受Object參数

Set set = prop.keySet();

for (Objectkey : set) {

Objectvalue = prop.get(key);

System.out.println(key + "---" + value);

}

}

16.Properties的特殊功能使用

特殊功能:

public Object setProperty(String key,String value):加入元素

public String getProperty(String key):获取元素

public Set stringPropertyNames():获取全部的键的集合

=========================

public static void main(String[] args) {

// 创建集合对象

Properties prop = new Properties();

// 加入元素

prop.setProperty("张三", "30");

prop.setProperty("李四", "40");

prop.setProperty("王五", "50");

// public Set stringPropertyNames():获取全部的键的集合

Set set = prop.stringPropertyNames();

for (String key : set) {

String value = prop.getProperty(key);

System.out.println(key + "---" + value);

}

}

================================================

17.Properties的load()和store()功能

这里的集合必须是Properties集合:

public void load(Readerreader):把文件中的数据读取到集合中

public void store(Writerwriter,String comments):把集合中的数据存储到文件

=================================================

public static void main(String[] args) throws IOException {

myLoad();

myStore();

}

private static void myStore() throws IOException {

// 创建集合对象

Properties prop = new Properties();

prop.setProperty("林青霞", "27");

prop.setProperty("武鑫", "30");

prop.setProperty("刘晓曲", "18");

//public void store(Writerwriter,String comments):把集合中的数据存储到文件

Writer w = new FileWriter("name.txt");

prop.store(w, "helloworld");//这个helloworld仅仅是凝视的作用。。。

w.close();

}

private static void myLoad() throws IOException {

Properties prop = new Properties();

// public void load(Readerreader):把文件里的数据读取到集合中

// 注意:这个文件的数据必须是键值对形式

Reader r = new FileReader("prop.txt");

prop.load(r);

r.close();

System.out.println("prop:" + prop);

}

执行打开name.txt文件

47641b9ba9f86d4f1e51bef12486a934.png

18.推断文件里是否有指定的键假设有就改动值的案例

我有一个文本文件(user.txt),我知道数据是键值对形式的,可是不知道内容是什么。

请写一个程序推断是否有“lisi”这种键存在,假设有就改变事实上为”100”

分析:

A:把文件里的数据载入到集合中

B:遍历集合,获取得到每个键

C:推断键是否有为"lisi"的。假设有就改动其值为"100"

D:把集合中的数据又一次存储到文件里

========================================

public static void main(String[] args) throws IOException {

// 把文件里的数据载入到集合中

Properties prop = new Properties();

Reader r = new FileReader("user.txt");

prop.load(r);

r.close();

// 遍历集合,获取得到每个键

Set 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);//这里设为null,不用附加东西了

w.close();

}

=============================================

user.txt

d5b51168c11371a94d2fa8564f0ff8ff.png

执行后

498484f925d36b0ce3ca7b072e311746.png

19.怎样让猜数字小游戏仅仅能玩5次案例

我有一个猜数字小游戏的程序,请写一个程序实如今測试类中仅仅能用5次,超过5次提示:游戏试玩已结束。请付费。

初始化:手动建一个文件保存玩游戏的次数(不须要写代码创建文件)

f5481664d2ddb93460bda2c01edabb70.png

public static void main(String[] args) throws IOException {

// 读取某个地方的数据。假设次数不大于5,能够继续玩。否则就提示"游戏试玩已结束。请付费。

// 把数据载入到集合中

Properties prop = new Properties();

Reader r = new FileReader("count.txt");

prop.load(r);

r.close();//别忘记关闭流

// 我自己的程序,我当然知道里面的键是谁

String value = prop.getProperty("count");

int number =Integer.parseInt(value);//String转换为int

if (number > 5) {

System.out.println("游戏试玩已结束,请付费。");

System.exit(0);//别漏了这一步退出!!

} else {

number++;

prop.setProperty("count", String.valueOf(number));//int转为String

Writer w = new FileWriter("count.txt");

prop.store(w, null);

w.close();//别忘记关闭流

GuessNumber.start();//这个猜数字的小游戏代码省略

}

}

注意几个问题:别忘记关闭流。注意字符串与Integer的转换.别漏了 System.exit(0)

==================================================

20.NIO的介绍和JDK7下NIO的一个案例

NIO:就是New IO

ead0ee5da4a834a4e7a9e3531ab20f7a.png

nio包在JDK4出现,提供了IO流的操作效率。可是眼下还不是大范围的使用。

有空的话了解下,有问题再问我。

JDK7的之后的nio:

Path:路径

Paths:有一个静态方法返回一个路径

public static Path get(URI uri)//返回值为Path

Files:提供了静态方法供我们使用

public staticlong copy(Pathsource,OutputStream out):拷贝文件

public staticPath write(Path path,Iterable extends CharSequence> lines,Charset cs,OpenOption... options)//后面那个可变參数就忽略不理,仅仅接受3个參数

===================================================

下面为课后阅读资料

1:JDK4新IO要了解的类(自己看)

Buffer(缓冲),Channer(通道)

2:JDK7要了解的新IO类

Path:与平台无关的路径。

Paths:包括了返回Path的静态方法。

public static Path get(URI uri):依据给定的URI来确定文件路径。

Files:操作文件的工具类。提供了大量的方法,简单了解例如以下方法

public static long copy(Path source, OutputStream out)

:拷贝文件

public static Path write(Path path, Iterable

extends CharSequence> lines, Charset cs, OpenOption... options):

把集合的数据写到文件。

//拷贝文件

Files.copy(Paths.get("Demo.java"), newFileOutputStream("Copy.Java"));

//把集合中的数据写到文件

List list = new ArrayList();

list.add("hello");

list.add("world");

list.add("java");

Files.write(Paths.get("list.txt"), list, Charset.forName("gbk"));

=================================================================================================

注意:ArrayList实现了Iterable接口

因此Iterable

extends CharSequence> lines相应的參数能够是ArrayList的对象

先測试copy功能

4c1738728ba995dc7ef69c26faa0d1d4.png

然后測试write功能

public static void main(String[] args) throws IOException {

ArrayList array = new ArrayList();

array.add("hello");

array.add("world");

array.add("java");

Files.write(Paths.get("array.txt"), array, Charset.forName("GBK"));

}

====================================================

下面是自己写的代码

9af33bec61412c4e44113be33d384d7e.png

Charset.forName("GBK")是设置编码的

===========

736116b7e2c3c14b8ef006fc159173d2.png

执行后

90dc3e7eeaa8fb338e9f95452c37e2e5.png

执行后

7d8392db61586ccdc47dd51fad5acdf4.png

===================================================

day22 笔记补充

登录注冊IO版本号案例(掌握)

要求,对着写一遍。

写的顺序參考:

cn.itcast.pojo User

cn.itcast.dao UserDao

cn.itcast.dao.impl UserDaoImpl(实现能够是集合版或者IO版)

cn.itcast.game GuessNumber

cn.itcast.test    UserTest

===============================================

内存操作流(理解)

(1)有些时候我们操作完成后,未必须要产生一个文件。就能够使用内存操作流。

(2)三种

A:ByteArrayInputStream,ByteArrayOutputStream

B:CharArrayReader,CharArrayWriter

C:StringReader,StringWriter

===============================================

打印流(掌握)

(1)字节打印流。字符打印流

(2)特点:

A:仅仅操作目的地,不操作数据源

B:能够操作随意类型的数据

C:假设启用了自己主动刷新。在调用println()方法的时候,可以换行并刷新

D:能够直接操作文件

问题:哪些流能够直接操作文件呢?

看API,假设其构造方法可以同一时候接收File和String类型的參数,一般都是可以直接操作文件的

(3)复制文本文件

BufferedReader br = new BufferedReader(new FileReader("a.txt"));

PrintWriter pw = new PrintWriter(new FileWriter("b.txt"),true);

String line = null;

while((line=br.readLine())!=null) {

pw.println(line);

}

pw.close();

br.close();

===============================================

5:标准输入输出流(理解)

(1)System类以下有这种两个字段

in 标准输入流

out 标准输出流

(2)三种键盘录入方式

A:main方法的args接收參数

B:System.in通过BufferedReader进行包装

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

C:Scanner

Scanner sc = new Scanner(System.in);

(3)输出语句的原理和怎样使用字符流输出数据

A:原理

System.out.println("helloworld");

PrintStream ps = System.out;//PrintStream 属于字节流

ps.println("helloworld");

B:把System.out用字符缓冲流包装一下使用

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

============================================================

序列化流(理解)

(1)能够把对象写入文本文件或者在网络中传输

(2)怎样实现序列化呢?

让被序列化的对象所属类实现序列化接口。

该接口是一个标记接口。没有功能须要实现。

(3)注意问题:

把数据写到文件后,在去改动类会产生一个问题。

怎样解决该问题呢?

在类文件里,给出一个固定的序列化id值。

并且,这样也能够解决黄色警告线问题

(4)面试题:

什么时候序列化?

怎样实现序列化?

什么是反序列化?

========================================================

NIO(了解)

(1)JDK4出现的NIO,对曾经的IO操作进行了优化,提供了效率。可是大部分我们看到的还是曾经的IO

(2)JDK7的NIO的使用

Path:路径

Paths:通过静态方法返回一个路径

Files:提供了常见的功能

复制文本文件

把集合中的数据写到文本文件

=============================================================

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值