Day 17
May 18, 2019.
This is the seventeenth day I learn Java.
On this day, I learned the following knowledge.
I 流
IO streams, to process the data transmission between devices, Java operations on the data stream by way of, for the Java object operations are IO stream packet
The data stream IO flows, it can be divided into: an input stream (the data read from the hard disk into memory), the output stream (from the memory to write data to the hard disk)
The data stream IO types can be divided into:
-
Byte stream
can read and write any type of file, such as audio, video, text files
abstract base class as follows:-
InputStream
conventional concrete subclasses: 1.FileInputStream
Constructor:FileInputStream(File file)
:Creates a FileInputStream by opening a connection to an actual file, the file specified by the File object file in the file system
FileInputStream(String name)
:Creates a FileInputStream by opening a connection to an actual file, the file specified by the pathname of the file system nameMembers of commonly used methods
- Read function
int read(byte[] b)
:Reads one byte array
- when the method returns -1, indicating that the data has been read. This value is generally available to determine whether data has been completed traversed
- Off function
public void close() throws IOException
:Close the file stream, free up resources
2.BufferedInputStream
order to correspond BufferedOutputStream, Java provided BufferedInputStream
constructor:BufferedInputStream(InputStream in)
:Create a BufferedInputStream and saves its argument, the input stream in, for later use - Read function
-
OutputStream
conventional concrete subclasses: 1.FileOutputStream
Constructor:FileOutputStream(File file)
:Create a file represented by the specified File object in writing data file output stream
FileOutputStream(String name)
:Writing data to create a file with the specified name of the output file stream
Members of commonly used methods- Write function
public void write(int b)
:Write a byte to cut in front of more than one byte bytespublic void write(byte[] b)
:Write a byte arraypublic void write(byte[] b,int off,int len)
:Write a byte array part
- Off function
public void close() throws IOException
:Close the file stream, free up resources
Interview questions: Why must close ()?
a: release notification system on the management of the resource file a.txt
b: let Io stream object becomes garbage, waiting for the garbage collector to reclaim their
2.BufferedOutputStream
byte stream read a first array of speed, much time was significantly faster than the speed of read and write a byte, which is added to the effect that the buffer array, java itself in the design, but also takes into account such design (explained later decorative design mode), thus providing a stream of bytes in the buffer, i.e. BufferedOutputStream
constructor:BufferedOutputStream(OutputStream out)
:Create a new buffered output stream to write data to the specified output stream bottom - Write function
-
-
Character stream
can only read and write text files
due to the byte stream operating Chinese is not particularly convenient, so, java provides a character stream
before introduction character stream, first introduced the concept of coding and decoding:-
Encoding
- converting a character string into a byte array
-public byte[] getBytes()
:Using the platform's default character set this String encoded as byte sequences, storing the result into a new byte array
-public byte[] getBytes(String charsetName)
:Using the specified character set coding this String is byte sequence, and storing the result into a new byte array -
Decoding
- the byte array to convert a string
-public String(byte[] bytes)
:Specified by the default character set decoding using the platform byte array, construct a new String
-public String(byte[] bytes, String charsetName)
:By using the specified charset decoding the specified byte array, construct a new String
Abstract base class as follows:
-
Writer
conventional concrete subclasses: 1.OutputStreamWriter - FileWriter (portable type)
Constructor:OutputStreamWriter(OutputStream out)
:The default encoding (GBK) byte stream data into a character stream
OutputStreamWriter(OutputStream out,String charsetName)
:According to a specified coding converts the byte stream data is character stream
Members of commonly used methods- Write function
public void write(int c)
:Write a characterpublic void write(char[] cbuf)
:Write an array of characterspublic void write(char[] cbuf,int off,int len)
:Write a character array partpublic void write(String str)
:Write a stringpublic void write(String str,int off,int len)
:Write part of a string
- Write function
2.BufferedWriter
efficient character output stream
constructor:public BufferedWriter(Writer w)
:Create one using the default buffer size of the output buffer character-output stream
Specialpublic void newLine()
methods: :The line feed system is determined, the system having compatibility newline l-
Reader
conventional concrete subclasses: 1.InputStreamReader - the FileReader (portable type)
Constructor:InputStreamReader(InputStream is)
:Reading data encoded with the default (GBK)
InputStreamReader(InputStream is,String charsetName)
:Read data with a specific code
Members of commonly used methods- Read function
public int read()
:Reads one characterpublic int read(char[] cbuf)
:Reads one character array, if not read, or -1
- Read function
2.BufferedReader
efficient character input stream
constructor:public BufferedReader(Reader e)
:Create one using the default buffer size of the input buffer character-input stream
Specialpublic String readLine()
methods: :A read data line, a line break is marked, read newline newline, not read data returns null -
IO streams exception handling
Exception handling IO stream into a byte stream and character stream
- Byte stream
in FileOutputStream for example, the following code
public class MyTest {
public static void main(String[] args) {
//流的异常处理
FileOutputStream out = null;
try {
out = new FileOutputStream("d.txt");
out.write(100);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- Jifuryu
In InPutStreamReader OutputStreamWriter and for example, the following code
public class MyTest {
public static void main(String[] args) {
//处理流的异常
//一次多写一些
InputStreamReader in = null;
OutputStreamWriter out = null;
try {
in = new InputStreamReader(new FileInputStream("MyTest.java"));
out = new OutputStreamWriter(new FileOutputStream("C:\\Users\\Administrator\\Desktop\\MyTest.java"));
//定义一个字符缓冲区
char[] chars = new char[2000];
int len = 0;//记录每次读取到的有效字符个数
while ((len = in.read(chars)) != -1) {
out.write(chars, 0, len);
out.flush();
}
} catch (IOException e) {
//处理逻辑,默认打印异常的详细堆栈信息
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Classical algorithm IO streams
- String data stored ArrayList set to a text file, text file and the data read into reverse ArrayList collection
code is as follows
//1.ArrayList集合中的字符串数组存储到文本文件
public class MyTest {
public static void main(String[] args) throws IOException {
//需求:把ArrayList集合中的字符串数据存储到文本文件
ArrayList<String> list = new ArrayList<>();
list.add("冯小刚");
list.add("张艺谋");
list.add("宁浩");
list.add("徐峥");
list.add("小四");
//把集合中的数据保存到文件文件中
//思路,遍历集合,取出数据写入文本文件
BufferedWriter writer = new BufferedWriter(new FileWriter("username.txt"));
for (String s : list) {
writer.write(s);
writer.newLine();
writer.flush();
}
writer.close();
}
}
//2.文本文件中的数据反向读入到ArrayList集合
public class MyTest2 {
public static void main(String[] args) throws IOException {
//需求是,把文本文件中的数据读取到集合中
ArrayList<String> list = new ArrayList<>();
BufferedReader reader = new BufferedReader(new FileReader("username.txt"));
while (true){
String s = reader.readLine();
if(s!=null){
list.add(s);
}else{
break;
}
}
System.out.println(list);
}
}
- Multi-level folder copy
the code below
public class HomeTest {
public static void main(String[] args) throws IOException {
//需求:复制多级文件夹
//1.封装源文件夹
File srcFolder = new File("C:\\test2");
//2.封装目标文件夹
File targetFolder = new File("D:\\test2");
if (!targetFolder.exists()) {
targetFolder.mkdirs();
}
//进行复制
copyFolder(srcFolder, targetFolder);
System.out.println("复制完成");
}
private static void copyFolder(File srcFolder, File targetFolder) throws IOException {
//遍历源文件夹下,所有的文件,复制到目标文件夹下去
File[] files = srcFolder.listFiles();
for (File f : files) {
if(f.isFile()){
copyFiles(f, targetFolder);
}else{
//targetFolder = new File(targetFolder.getPath() + "\\" + f.getName());
//递归
File file = new File(targetFolder,f.getName());
if (!file.exists()) {
file.mkdirs();
}
copyFolder(f, file);
}
}
}
//复制文件
private static void copyFiles(File f, File targetFolder) throws IOException {
//使用字节流来复制
FileInputStream in = new FileInputStream(f);//封装源文件
//封装目标文件
//File file = new File(targetFolder, f.getName());
//System.out.println(file);
FileOutputStream out = new FileOutputStream(new File(targetFolder, f.getName()));
int len = 0;
byte[] bytes = new byte[1024 * 8];
while ((len = in.read(bytes)) != -1) {
out.write(bytes, 0, len);
out.flush();
}
//是否资源
in.close();
out.close();
}
}
- Input student information to a file
code is as follows
//学生类
public class Student implements Comparable<Student>{
private String name;
private int score;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.score = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return score;
}
public void setAge(int age) {
this.score = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", grade=" + score +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return score == student.score &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, score);
}
@Override
public int compareTo(Student o) {
int num=this.score-o.score;
int num2=num==0?this.name.compareTo(o.name):num;
return num2;
}
}
//测试类
public class HomeTest {
public static void main(String[] args) throws IOException {
//需求: 键盘录入学生信息按照总分排序并写入文本文件
Scanner scanner = new Scanner(System.in);
Student student;
TreeSet<Student> treeSet = new TreeSet<>();
BufferedWriter buf = new BufferedWriter(new FileWriter("Student.txt"));
for (int i = 1; i < 4; i++) {
scanner = new Scanner(System.in);
student = new Student();
System.out.println("请输入第" + i + "位学生的姓名");
String name = scanner.nextLine();
student.setName(name);
System.out.println("请输入第" + i + "位学生的成绩");
int score = scanner.nextInt();
student.setAge(score);
treeSet.add(student);
}
buf.write(treeSet.toString());
buf.close();
}
}