java foundation---IO (below)

java foundation - IO (below)

1. Conversion flow

  • Origin of conversion stream:

    1. A bridge between character streams and byte streams.

    2. It is convenient to operate between character stream and byte stream.

  • Application of conversion stream: When the data of the byte stream are all characters, it is more efficient to convert to a character stream.

  • Transform stream:

    1. InputStreamReader: Byte-to-character bridge, encoding.

    2. OutputtreamWriter: Character-to-byte bridge, decoding.

  • Example:

    • Requirement: Write the following code with the conversion flow to obtain the data entered by the user's keyboard and display the data in uppercase on the console. If the user's input is over, end the keyboard entry.
import java.io.*;
class ReadKey1
{
    public static void main(String[] args) throws IOException
    {
        //将键盘录入数据与输入流相关联,字节流转换成字符流
        BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
        String line=null;
        while ((line=bufr.readLine())!=null)
        {
            //若输入“over”,则结束键盘录入
            if (line.equals("over"))
            {
                break;
            }
            //将键盘录入的数据转换成大写
            System.out.println(line.toUpperCase());
        }
    }
}
  • Output result:

Second, the flow rate of operation

  1. Identify source and purpose

    • 源:IuputStream Reader

    • 目的:OutputStream Writer

  2. Determine if the data is plain text data

    • Source: Yes Plain Text: Reader; No: InputStream

    • Purpose: Yes Plain Text: Writer; No: OutputStream

    • Remarks: Here you can specify which system to use in the requirements.

  3. Identify specific equipment

    • Source device:

      • Hard Disk: File

      • Keyboard: System.in

      • memory: array

      • Network: Socket Streaming

    • Destination device:

      • Hard Disk: File

      • keyboard: System.out

      • memory: array

      • Network: Socket Streaming

  4. Do you need other extra features

    • Whether it needs to be efficient (buffer): yes, add buffer

3. File class

  • Definition : The File class is used to encapsulate files or folders into objects, which is convenient for manipulating the attribute information of files and folders.

  • Role : The File object can be passed as a parameter to the constructor of the stream.

  • Common methods of File objects:

    1. Obtain

      • Get file name: String getName();

      • Get the file path: String getPath();

      • Get file size: long length();

      • Get file modification time: long lastModified();

    2. Create and delete

      • boolean createNewFile(); Creates a new empty file if the file does not exist.

      • boolean delete(); Deletes the file or directory represented by this abstract pathname.

    3. judge

      • boolean exists(); Determines whether the file or directory exists.

      • boolean isFile(); Tests whether the file represented by this abstract pathname is a standard file.

      • boolean isDirectory(); Tests whether the file represented by this abstract pathname is a directory.

    4. Rename

      • boolean renameTo(File dest); Renames the file represented by this abstract pathname.
    5. System root directory and capacity acquisition

      • Sting[] list(); Returns an array of strings specifying the files and directories in the directory represented by this abstract pathname.

      • long getFreeSpace(); Returns the number of unallocated bytes in the partition specified by this abstract pathname.

      • long getTotalSpace(); Returns the size of the partition specified by this abstract pathname.

      • long getUsableSpace(); Returns the number of bytes available to this virtual machine on the partition specified by this abstract pathname.

  • Example:

    • Code:
        File f=new File("file.txt");//创建一个File实例
        boolean b1=f.exists();//判断此文件是否存在
        System.out.println(b1);
        if(!f.exists())
        {
            f.createNewFile();//若文件不存在,则创建一个新的空的文件
        }
        if(f.exists())
        {
            System.out.println(f.isFile());//若文件存在,则判断此文件是否是个标准文件
        }
        f=new File("abc\\ab");
        f.mkdirs();//创建目录
        if(f.exists())
        {
            System.out.println(f.isDirectory());//若存在,则判断此文件是否是个目录。
        }

4. Recursion

  • Definition: The function itself directly or indirectly calls itself. A function is used repeatedly, and each time it is used, the result of the operation involved is related to the previous call. In this case, recursion can be used to solve the problem.
  • Example
    • Requirement: List all contents of the specified directory (including the contents in subdirectories), which can also be understood as deep traversal.
    • Code:
import java.io.*;
class  FileListDemo
{
    public static void main(String[] args) 
    {
        //将java2015文件夹封装成对象;
        File dir=new File("D:\\java2015");
        listAll(dir,0);     
    }
    public static void listAll(File dir,int level)
    {
        System.out.println(getSpace(level)+"dir:"+dir.getAbsolutePath());
        level++;
        //获取指定目录下的文件和文件夹
        File[] files=dir.listFiles();
        for(File file:files)
        {
            //若获取的为文件夹则继续获取子文件中的内容
            if(file.isDirectory())
                listAll(file,level);
            //将获取的文件打印到控制台上
            else
            {
                System.out.println(getSpace(level)+"file:"+file);
            }
        }
    }
    //获取标记,显示获取的文件夹或文件在指定目录中的层级。
    private static String getSpace(int level)
    {
        StringBuilder sb=new StringBuilder();
        sb.append("|--");
        for (int x=0;x<level ;x++ )
        {
            sb.append("|--");
        }
        return sb.toString();
    }
}
  • Output result:
    write picture description here

Five, Properties collection

  • Map

    • |–Hashtable
      • |–Properties
  • Features:

      1. Both keys and values ​​in this collection are of type string.
      1. Data in a collection can be saved to a stream, or retrieved from a stream.
      1. Typically this collection is used to manipulate configuration files in the form of key-value pairs.
  • Common method :

    • setProperty(); stores the element.

    • getProperty(): Searches this property list for a property with the specified key.

    • stringPropertyNames() : Returns the set of keys in this property list.

    • list(PrintStream out) : Print the property list to the specified output stream.

  • Example :

    • Code:
import java.util.*;
import java.io.*;
class PropertiesDemo
{
    public static void main(String[] args)throws IOException 
    {
        Properties p=new Properties();
        //添加元素
        p.setProperty("zhangshang","20");
        p.setProperty("lisi","24");
        p.setProperty("xupeng","23");
        //修改元素
        p.setProperty("xupeng","25");
        //获取p的键集
        Set<String> names=p.stringPropertyNames();
        //将键值对打印出来
        for(String name:names)
        {
            String value=p.getProperty(name);
            System.out.println(name+":"+value);
        }
    }
}
  • Output result:
    write picture description here

6. Other streams in the IO package

  • Print stream : PrintWriter and PrintStream (can directly manipulate input streams and files)

    • PrintStream:

      1. Provides a print method that can print values ​​of various data types and maintain the representation of the data.

      2. it doesn't throw IOException

      3. Constructor that accepts three types of values:

        1. string path

        2. File object

        3. byte output stream

    • PrintWriter: character print stream

      • Constructor parameters

        1. String road strength

        2. File object

        3. byte output stream

        4. character output stream

  • Sequence stream : SequenceInputStream (merge multiple streams)

  • Object streams : ObjectInputStream and ObjectOutputStream

    • Note: The object being manipulated needs to implement the Serializable interface.
  • RandomAccessFile

    • Random access files have their own methods of reading and writing.

    • Random access is achieved by skipBytes(int x), seek(int x), etc.

    • Features:

      1. The object is both readable and writable.

      2. The object internally maintains a byte array, and the elements in the array can be manipulated through pointers.

      3. The position of the pointer can be obtained through the getFilePointer method, and the position of the pointer can be set through the seek method
        .

      4. In fact, the object is to encapsulate the byte input stream and output stream.

      5. The source or destination of this object can only be a file. It can be seen through the constructor.

  • Piped stream : PipedInputStream and PipedOutputStream (input and output can be directly connected by
    combining threads)

  • Manipulate basic data types : DataInputStream and DataOutputStream

  • Manipulating byte arrays : ByteArrayInputStream and ByteArrayOutputStream

    • Features: Closing byte array input and output streams has no effect, because they do not call the underlying resources, and all operations are done in memory.

7. Code table

  • The origin of the coding table: The computer can only recognize binary data, and the early origin was electrical signals. In order to facilitate the application of the computer, it can recognize the characters of various countries. The characters of each country are represented by numbers and correspond one by one to form a table, which is the coding table.

  • Common coding tables:

    • ASCII: American Standard Information Interchange Code, which can be represented by 7 bits of a byte.

    • ISO8859-1: Latin code table. Eurocode table, represented by 8 bits of a byte.

    • GB2312: Chinese code table for China.

    • GBK: China's Chinese code table has been upgraded, incorporating more Chinese characters.

    • Unicode: International Standard Code, which combines a variety of scripts. All text is represented by two bytes, and the Java language uses unicode

    • UTF-8: Use up to three bytes to represent a character.

  • Example:

    • Code:
import java.io.*;
class EncodeDemo 
{
    public static void main(String[] args) throws Exception
    {
        String str="您好";
        //字符串-->字节数组:编码
        //字符数组-->字符串:解码

        //编码
        byte[] buf1=str.getBytes("GBK");//GBK编码表
        printBytes(buf1);

        byte[] buf2=str.getBytes("UTF-8");//UTF-8编码表
        printBytes(buf2);

        //解码
        String s1=new String(buf1);
        System.out.println("s1="+s1);

        String s2=new String(buf2,"UTF-8");
        System.out.println("s2="+s2);
    }
    //将字节数组打印出来
    private static void printBytes(byte[] buf)
    {
        for(byte b:buf)
        {
            System.out.print(b+""+"\t");
        }
        System.out.println();
    }
}
  • Output result:
    write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325518990&siteId=291194637