Java Study Notes (5)-file and security

Source: Internet
Author: User
Tags define local
9.1 java. Io Overview

1. The data stream is a continuous byte block. In terms of concept, one end of a stream can be connected to a data source or receive data, and the other end can be considered to be connected to classes in the Java. Io package.
 
2. streams connected to the data source are used to read data from the source. the I/O class can read bytes from the stream, and the stream can supplement bytes from the data source. This type of stream is called an input stream.
 
3. Streams connected to the data receiver are used to write data to the receiver. java. I/O classes connected to the data receiver can insert bytes into the stream and send the bytes to the data receiver.

 
4. byte-level input/output class structure level:
Inputstream outputstream
Fileinputstream fileoutputsteam
Filterinputstream filteroutputstream
Bufferedinputstream bufferedoutputstream
Datainputstream dataoutputstream
 
 
5. Character-level input/output class structure level:
Reader writer
Bufferedreader bufferedwirter
Linenumberreader printerwriter
Inputstreamreader outputstreamwriter
Filereader filewriter
 
6. Object-level input/output class structure level:
Inputstream outputstream
Objectinputstream objectoutputstream
 
9.2 save and read byte data:

1. dataoutputstream writes a basic java data type to the output stream. The written data is portable, which is unrelated to the specific operating system.

2. The fileoutputstream class connects the output stream to a file to prepare for writing data to the file.

3. If you create a fileoutputstream object with an existing file name, the file will be replaced by a new empty file without any warning. We can use the methods provided by the file or filedialog class to prevent accidental deletion of important files.
 
4. Use the dataoutputstream class and the fileoutputstream class to write data to a file:

5. The datainputstream class reads the basic data type of Java from an input stream in a machine-independent manner. An eofexception occurs when any method reads data over-the-current tail.
 
6. The fileinputstream class reads bytes from an existing file and returns an input stream connected to the file.

7. How to read data from a file using the datainputstream class and fileoutputstream class:

 
8. the bufferedoutputstream class enhances the ability of batch data output to another output stream. Data is first written to an internal buffer, and is written to the stream only after the buffer is full. When the stream is closed, if the buffer is not full, the data is forced into the input stream. All the operations on the output stream are automatically buffered.

9. How to write data to a file using the dataoutputstream class, fileoutputstream class, And bufferedoutputstream class:

10. The file class is used to represent a file, a directory name, or a combination of a directory name and a file name. The file name used is related to the high level system.

11. Related APIs:
Getname (): Get file name getpath (): Get path
Exists (): determines whether the specified file exists in isdirectory (): determines whether the path is
Isfile (): determines whether a file is listfiles (): returns an array of file objects in a specified directory.

12. You can use system .. getproperty ("user. dir") to ensure that the current directory is used if the user does not provide a directory.

13. The sorting method is as follows:
1) create a class to implement comparator, and implement the abstract method compare (Object O1, object O2) in the class)

2) Call the sort (Object A [], comparator c) Method of the arrays class in the main program to sort the objects in array A by the methods in the interface.
 
9.3 save and read character data:
1. The bufferedreader class reads text from the character input stream and stores the characters in the cache if necessary. As long as the text contains a line feed, carriage return, or carriage return, it is considered that a line of text ends. If these symbols are not present in the stream, the Readline method returns NULL without throwing an exception.

2. The filereader class can easily connect a file to other classes that require reader as input parameters.

3. Use the bufferedreader class and filereader class to write data to a file:

4. the filedialog class contains the standard "file | open", "file | save" dialog box, which can be read or written by selecting a file. The dialog box is a modal dialog box, once opened through setvisible or show, only by selecting a file or canceling can she disappear. This dialog box contains the OK and cancel buttons. If you select cancel, the GetFile () method returns NULL. If the creation mode of this dialog box is save, the user must confirm before overwriting an existing file.

5. Related APIs:
Getdirectory (): Get file path GetFile (): Get File Name
6. The bufferedwriter class is used to create a character buffer output stream. It is mainly used by other classes to input a character stream.
7. The printwriter class provides some practical methods for formatting the intent stream. This class does not throw any exceptions. Instead, it uses checkerror to check whether an error has occurred before calling this method.
8. the filewriter class connects the character output stream to the file. The filewriter will delete an existing file without any prompt. Therefore, the file class or the filedialog class provides the method, make sure that your important files are not accidentally deleted.
9. Use the printwriter class, bufferedwirter class, And filewriter class to write data to the file:

 
9.3 save and read Object Data
1. Queue list class: can be used as a stack, queue, and bidirectional queue
2. Common APIs:
Add (INT index, object element): Add an object to the list
Get (INT index): returns the object at the specified position.
Contains (Object O): determines whether the specified object is contained in the listing list.
Index (Object O): returns the subscript of an object.
Set (INT index, object O): replace the original object at the specified position with the specified object
Remove (INT index): removes an object from a specified position.
3. The iterator interface simplifies the process of all sequential processing of list elements in the java standard list structure by improving the sequential access list elements.
4. the Java API definition class iterator is as follows:
Boolean hasnext (): determines whether the current pointer has pointed to the end of the list.
Object next (): returns the current object and points an internal pointer to the next element in the list.
5. iterator objects can be created through the iterator method. The iterator method is a method in the list interface, so it is part of all the standard Java list structures. Iterator allows you to process elements in a table continuously through a fast and simple for loop.
For (iterator = List. iterator (); iterator. hasnext ();)
System. Out. println (iterator. Next ());
6. The objectoutputstream class is used to write the original data type and the entire object into the stream. To write objects to objectoutputstream, the class to which the object belongs must be Java. io. serializable interface, the default mechanism for writing an object is to write its original Class, Class features, non-transient (non-transient) of the class, that is, non-static member variables. A class implements the serializable interface so that the objects of this class can be written to the objectoutputstream stream, and these objects can be read through the objectoutputstream stream.

7. The objectinputstream class is used to read the original data type and the entire object written to the stream using objectoutputstream. It also uses the Java type conversion mechanism to restore the object type.

8. serialization is very convenient to use, but it also introduces a security issue, because the data stored in the disk is independent of the object, there is no way to protect the data from being modified, when the data is re-read, an invalid time is generated. In addition, private data is protected in the object and cannot be processed externally. Once written to the disk, private data may be exposed to external operations.

9. If the object and security are important, you can use the default serialization object method instead of overwriting the original operators to customize the order columns.
Public void readobject (objectinputstream in) throws ioexception, classnotfoundexception
{/* Custom Method for reading objects */}
Public void writeobject (objectoutputstream out) throws ioexception
{/* Custom writing object Method */}
Public void writeobject (objectoutputstream out) throws ioexception
{Throw noaccessexception}
 
9.4 applet file operations and security
1. Before a Java class is executed, JVM must perform security and violation checks on it. Even in the running process, each Java class must be controlled by the security manager so that it can only access resources that it has the right to access. If it tries to access resources that it has no permission to access, the security manager rejects the request and throws a securityexception.

2. The custom security manager cannot be used in the web browser. Using the applet in the Web browser must be subject to the security restrictions of the Web browser.
3. the applet is executed in the sandbox. That is to say, the applet can be executed in a pre-defined area of the computer and cannot exceed this range. The security manager supervises the access. If the applet attempts to access resources other than the sandbox, the security manager rejects the access and throws an exception. The following security restrictions apply to the Applet:
1). the applet cannot directly read and write files.
2). the applet can be connected to the network only through the host where it is located.
3). the applet cannot execute the local program of its host (that is, the program written in other languages)
4). the applet cannot read or modify system attributes.
5) a window appears when the applet is executed. The window looks different from the standard window.
6). The applet cannot define local methods (that is, Methods written in other English languages ).
 
4. As long as the file is explicitly declared as a "public file", the applet can read data from the file. The so-called "public file" is a file located in a public readable folder on the Web server.

5. How to read files in the Applet:
1) the data file and Applet must be physically located on the same machine.
2). The data file and Applet are either on the local machine or in the public area of the Web server.
3). You must use the URL class to connect to the data file instead of fileinputstream.
4). This method is only applicable to input streams and does not apply to output streams.
6. The inputstreamreader class is a bridge between byte streams. It reads bytes and converts them into characters. It uses the default encoding of the platform and can also specify another encoding.
7. Like filereader, inputstreamreader can connect to a bufferedreader to achieve better efficiency.

9.5 system I/O Stream
1. The system class protects three static member variables. They describe three common streams of the class. These streams are opened at any time and ready to transfer and accept data.

2. system. Out: printstream type system. In: inputstream type system. Err: printstream type

3. setout (printstream out): Re-specify system. out as the output stream out.
Setin (inputstream in): Re-specify system .. in as the input stream in
Seterr (printstream out): Re-specify system .. err as the output stream out

4. Redirecting system .. out or system. Err is useful for programs that need to print status and debugging information.
 
9.6 randomaccessfile
1. randomaccessfile instances support reading and writing files at the same time.
2. for all read operations on this class, if the specified number of bytes have not been read, but the file pointer has executed the end of the file, an ofexception exception will be thrown, if it cannot be read for other reasons, an ioexception instead of eofexeption will be thrown;
In particular, if the file is closed and then read/write operations are performed, an ioexception is thrown.
3. randomaccessfile can be used to read and write text and Java base data types in addition to the bytes at any position in the file.
4. Common APIs:
Randomaccessfile (string filename, string mode): the mode is the operation mode, indicating that the file is in the "R" or "RW" mode.
Randomaccessfile (File file, string mode): file is the specified file object.
Read (): read data from a file
Read (byte [] B): reads data from the current pointer to the array until it is full.
Readline (): Read the next line of text in the current file
Seek (): set the current file pointer

9.7 others
1. Steps for loading and displaying images:
1). Obtain the path of the image file, file name:
URL url = new URL (URL context, string filename) // context can be obtained through getcodebase ()
2). Get the image file using the default Toolkit:
Image = toolkit. getdefatooltoolkit (). getimage (URL)
3) Add the image to the mediatracker Class Object and load it:
Mediatracker tracker = new mediatracker (this );
Tracker. addimage (image, 0); // Add the image to tracker and set the priority to 0 (highest)
Tracker. waitforall (); // suspends any operation until all images are fully loaded.
4). Call the drawing method to draw a picture:
Repaint ()
 
2. Because an exception may be triggered during image loading, capture
3. The image format obtained through getimage (URL) can only be GIF, jpea, or PNG.
4. the inset object is used to specify the border format of a container, that is, the distance between the container and the border. The space can be a border, blank area, or title. The construction method is new inset (INT top, int left, int bottom, int right)
5. The getinset () method specifies how much content can be received when a layout manager is deployed.
6. 3D border painting with titles:
W = getfontmetrics (font). stringwidth (title); // return the string degree displayed in the specified font.
H = getfontmetrics (font). getmaxascent () + 1; // return the font height displayed in the specified font.
D = H/2; // specifies the distance between the Drawing start point and border.
Bgcolor = color. White; // used to specify the image background
Font = new font ("Helvetica", Font. Bold, 12); // specifies the font to display.
Public void paint (Graphics g ){
G. setcolor (color. Gray );
G. drawrect (D, D, getsize (). Width-2 * D, getsize (). Height-2 * D); // used to draw the widget border
 
G. setcolor (color. Black );
G. drawline (getsize (). Width-D + 1, D
Getsize (). Width-D + 1, getsize (). Height-D + 1); // It is used to draw the three-dimensional border (vertical) of the component)
G. drawline (D, getsize (). Height-D + 1
Getsize (). Width-D + 1, getsize (). Height-D + 1); // It is used to draw the three-dimensional border (horizontal) of the component)
 
G. setfont (font );
G. setcolor (bgcolor );
G. fillrect (INT) (1.5 * H)-, W + 10, H + 2); // draws the border of the title.
G. setcolor (color. Black );
G. drawstring (title, (INT) (1.5 * H), H-2); // used to display the title in the border
}
 
7. Common drawing APIs:
1). drawline (INT X1, int Y1, int X2, int Y2 ):
Draw a straight line between a vertex (x1, Y1) and a vertex (X2, Y2)
2). drawrect (int x, int y, int width, int height ):
Draws a rectangle with the width and height at the point (x, y) as the origin.
3). drawroundrect (int x, int y, int width, int height, int arcwidth, int archeight ):
Start from the point (x, y) to draw a width, height for height, horizontal and vertical radian diameter for arcwidth, archeight rectangle
3). draw3drect (int x, int y, int width, int height, Boolean raised ):
Draw a 3D rectangle with the width and height at the point (x, y) as the origin. Raised determines whether the rectangle is convex or concave.
4). drawstring (string STR, int X, int y ):
Write a string from a vertex (x, y ).
5). drawimage (image IMG, int X, int y, imageobserver observer ):
Start drawing as much as possible at the point (x, y) and return the information to the corresponding imageobserver object in time.

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.