201621123031 Java programming 12th Week of study summary

Source: Internet
Author: User

Job 12-Stream vs. file 1. This week's study summary 1.1 summarizes multi-stream and file-related content in the way you like (mind map or other).

In a package in Java, java.io many classes are defined to handle input and output in a variety of ways. All of the input stream classes are subclasses of abstract classes InputStream (byte input streams) or abstract classes Reader (character input streams), and all output stream classes are OutputStream subclasses of abstract classes (byte output streams) or abstract classes Writer (character output streams).

1. Input stream

InputStreamHierarchy of Classes

ReaderHierarchy of Classes

2. Output stream

OutputStreamHierarchy of Classes

WriterHierarchy of Classes

3.File class

The file class is the java.io only object in the package that represents the disk file itself. The file class defines a platform-independent approach to manipulating files, and allows you to create, delete, rename, and so on, by calling methods in the file class. The object of the file class is primarily used to obtain information about the files themselves, such as the directory where the file resides, the length of the file, the file read and write permissions, and so on. Data streams can write data to a file, which is also the most commonly used data medium for data flow.

1. Creation of files
(1).New File(String pathname)
The construction method creates a new file instance by converting the given pathname string to an abstract path name
(2).new File(String parent,String child)
The construction method creates a new file object based on the defined parent path and subpath string
(3).new File(File f,String child)
The construction method creates a new file instance based on the parent abstract pathname and the child path string
2. Get file information
Common methods for file classes

Method return value Description
GetName () String Gets the name of the file
CanRead () Boolean Determine if the file is readable
CanWrite () Boolean Determine if a file can be written
Exits () Boolean Determine if a file exists
Length () Long Get file length
Getabsoultepath () String Gets the absolute path of the file
GetParent () String Gets the parent path of the file
Isfile () Boolean Determine if a file exists
Isdirectory () Boolean Determine if a file is a directory
Ishidden () Boolean Determine if a file is a hidden file
LastModified () Long Get file Last modified time
2. System-oriented integrated design-Library management system or shopping cart

Use streams and files to transform your library management system or shopping cart.

2.1 A brief description of how to use streams and files to transform your system. What is the format of the data in the file?

A: I started with a static initialization block initial library data and then the initialization of the book data using object flow to ObjectOutputStream write files Book.data to save, the user module is similar, Then write a method that saves the modified file data in two modules for storing the file after the data changes in the operation. Writing to a file with an object stream is saved in hexadecimal because the object flow is inherently suitable for transmission between networks.

2.2 Brief description of what interfaces and classes are used in the file reading and writing section of the system with the stream associated with the file? Why use these interfaces with classes?

Used, the InputStream OutputStream interface ObjectInputStream and sub-class, as well as the ObjectOutputStream file class File , when the object is serialized in the use of the Serializable interface, the use of object flow is to be able to put an object's complete information into the file, If the normal byte stream is not the way to do this, and then use the object stream to write or read objects, to ensure that the object is serialized, this is to ensure that the object can be written to the file, and read from the file correctly into the program, this time to use the Serializable interface to implement the object serialization.

2.3 Read and write file-related code. Critical lines need to be annotated.

Initialize Library :


Save the modified Library file:

Initialize the user module:

Save the modified user information to a file:

Option: 3. Try to design a search engine system for the computer Academy website (Team completion)

You can start with the console only, not necessarily with the web.

3.1 The system is probably divided into several parts, each part to complete what function? 3.2 What is the entire workflow of the system. What is the relationship between the various parts. You can try drawing description. 3.3 What knowledge is needed to complete the system? 3. Code volume Statistics 3.1 Statistics the amount of code completed this week

The weekly code statistics need to be fused into a single table.
Seems to have reached the goal set for the first week (? ˙▽˙?)

Week Time Total code Amount New Code Volume total number of files number of new files
2 607 607 15 15
3 1642 1035 33 18
5 2044 402 42 9
6 2874 830 57 15
7 3161 287 63 6
8 4299 1138 72 9
9 4831 532 81 9
10 5475 644 93 12
11 5958 483 102 9
12 6819 861 116 14
13 7408 589 127 11
Option: 4. Flow and Document Learning Guide (the job content is all selected at the bottom) 1. Character stream with text file: Use PrintWriter (write), BufferedReader (Read)

Writes the Student object (property: Int id, String name,int age,double grade) to the file Student.data, read from the file display.

1.1 Generated three student objects, using PrintWriter's Println method to write Student.txt, one student per line, and each student's attribute separated by |. Use scanner or BufferedReader to read the Student.txt data. (Key code, occurrence number)

Three X Student objects:

Writestudent Method:

Read Student.txt using the BufferedReader method

Console output and Notepad content:

1.2 What is the size of the generated file (using the right-click File Properties view)? Analyze the file size



The file size is 48 bytes, with each English character and the ' | ' Takes up one byte, each Chinese character occupies two bytes, and the newline character occupies two bytes, so each behavior is 16 bytes, and three lines total 48 bytes.

1.3 If the println method of PrintWriter is called, but not close at the back. What is the file size? Why?

The size is 0 bytes.
Because Printwrite writes data to a buffer, it sends out the contents of the buffer when close is last used, so the data is lost in the buffer when close is not used. Therefore, if the flush method is used before closing to send the contents of the buffer first, the data can be written to the file.

2. Buffer Stream 2.1 Use PrintWriter to write 10 million lines to a file (whatever it is), and then compare the speed (read only, not output) of using BufferedReader to read data from the file using scanner, which method is used fast? Intercept the test source code, the number of the study. Please analyze the reasons in detail. Tip: You can use JUNIT4 to compare run times





It can be seen that the use of BufferedReader read files is faster, because the Scanner input data is parsed as a class, but BufferedReader only a sequence of characters is simply read. and BufferedReader with a larger Scanner buffer, fewer input and output operations are possible, so it's faster.

2.2 Replace the PrintWriter with BufferedWriter to see if the speed of writing to the file has improved. Record the elapsed time of both. Try to analyze the reason.




As you can see, the speed is improved because the BufferedWriter has a larger buffer relationship.

3. Character encoding 3.1 Existing EncodeTest.txt file, contains some Chinese, the file is encoded using UTF-8. Use FileReader and BufferedReader to read the EncodeTest.txt text into and out. Do you have garbled characters? Why does it have garbled characters? How to solve? (Key code, occurrence number)


Operation Result:

It can be seen that it is garbled, because FileReader it inherits from InputStreamReader , and uses it to complete the conversion of the byte stream to the word stream, and the character set taken at the time of conversion is the system's default character set, which is GBK. So in the process of UTF-8---GBK---UTF-8, the loss of code, resulting in a garbled appearance. Here's how to fix it:

3.2 Writing methodsconvertGBK2UTF8(String src, String dst), you can convert the GBK encoded source file src to the UTF8 encoded destination file DST.

Here's how:

4. Byte stream, binary file: DataInputStream, DataOutputStream, ObjectInputStream4.1 reference DataStream directory related code, try to write three student object data to the file, It is then read out and displayed from the file. (Key code, occurrence number)





4.2 The file generated here and Topic 1 generated files why not the same? How large is the generated file? Parse the file size? Compare the file size to the file generated by topic 1 is it big or small, why? When it comes to storing data, is it easier to save space in binary files or text files? What are the benefits of using a binary storage file?

The file generated here is a data file with a suffix of the. Data, in this case a binary file.

You can see that the resulting file is 72 bytes, one int is 4 bytes, one character is 3 bytes, that the string occupies 2 bytes, a double is 8 bytes, so the number of bytes in a row is 4+3+3+4+8+2=24, and the number of bytes in the three row is 24*3=72.
And the title of the file is larger than the above analysis can be seen, the storage of a int,double and Chinese characters required more bytes, so the file is larger than the first question.
Although the above analysis seems to be a text file more space-saving, but this still depends on the situation, when the stored value is very small, the text file may occupy a smaller space, but if you want to store a large amount of data, or binary files can save space.
The benefits of using binary storage files are as follows:

    • Binary files save more storage space
    • For some more accurate data, the binary does not cause the loss of a significant number of digits
    • The language used in a computer is a binary language, so binary storage saves you from the language conversion process
4.3 Use the Wxmedit 16 binary mode (or the 16 binary mode of other text editors) to open Student.data and analyze how the data is stored in the file.


A little lazy, just analyze a row, the remaining two lines are similar:
00 00 00 01 Representative1
00 06 represents the number of bytes occupied by the character, one Chinese character occupies three bytes
E5 BC A0 E4 B8 89 rep张三
00 00 00 13 stands for ' 19 '
40 50 40 00 00 00 00 00 Representative19.65

4.4 Use ObjectInputStream (read), ObjectOutputStream (write) Read and write students. (Key code, Advent Number)//reference Objectstreamtest Directory



5. Scanner Basic Concept Assembly object

Writes public static List<Student> readStudents(String fileName) All students from the text file specified by filename and puts it in a list. Should I use those IO-related classes? Tell me about your reasons for choosing.


A: The class to be used has the file class, the FileInputStream class, the InputStreamReader class, the BufferedReader class, where the large buffer in the BufferedReader class allows us to read and write the data more quickly.

6. Select: RandomAccessFile6.1 use Randomaccessfile to achieve topic 1.1. (Key code, occurrence number)




6.2 Analyzing file sizes


The size is 72 bytes, and the analysis in 4.2 is the same.

6.3 Writing a functionpublic Student getStuByIndext(int index), you can use Randomaccessfile to remove the student's information from the file according to the ordinal index. (The key code, the occurrence of the school number). And answer, where is the randomaccessfile of the random access characteristics of the file.




RandomAccessFileYou can seek() skipBytes() length navigate to any location in the file by, and so on, some file operations at this base location.

7. File operation

Write a program, according to the specified directory and file name, search for the directory and all files under the subdirectory, if the specified file name is not found, then show no match, otherwise all the found file names and folder names are displayed.

7.1 Writingpublic static void findFile(String path,String filename)function, the path specified by path is the root directory, using recursion, in its directory and subdirectories to find all and filename the same file name, once found on the output to the console immediately. (Key code, occurrence number)



7.2 Use the queue, use the graphical interface, complete with Java nio.2 (optional 1)




Nio.2 's File tool class provides a way walkFileTree to traverse, more efficient and elegant than the previous one, and then uses the traversal behavior controller internally, FileVisitor which is an interface that provides four methods to specify event handling during traversal, but in fact, I use the direct inheritance adapter when I traverse FileVisitor SimpleFileVisitor , it is compared FileVisitor with the advantage is that can not implement four methods, only need to implement the required method. However, it is found that files traversed with nio.2 do not seem to be case-sensitive.

7.3 Choose: Performance test, Test your findfile to find the speed of matching files. There are solutions that can make finding faster. For example, similarEverythingThe search speed.

findFilerun speed of test:

Run time with normal traversal:

Traversal time using the Nio.2 method:

Through the above image can be seen, the use of nio.2 running time is shorter, in fact, the title said that the use of nio.2 can improve the efficiency of the traversal.

7.4 Optional: Implementation deletes the specified directory (if the directory is not empty, delete all files and directories under that directory and its subdirectories).

7.5 Select: Convert all. java files in the specified directory and subdirectories into UTF-8 encoded format and test.




8. Regular expression 8.1 uses regular expressions to determine whether a given string is a 10-digit format? Try programming to validate, to give the test data set and run the result (can be converted to PTA). (Key code, occurrence number)


8.2 Explain the regular expression you wrote.

The regular expression I wrote is^[-\\+]?[\\d]+[\\.]?[\\d]+$
^Represents the starting position of the matching input string
[-\\+]?Represents the string "-" and "+" can occur 0 or 1 times
[\\d]+Represents a number that can occur 1 or more times
[\\.]?Represents "." can occur 0 or 1 times
$Represents the end position of the matching input string

201621123031 Java programming 12th Week of study summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.