Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Java method to read and write files summary     - RHEL6.4 x86_64 build SVN service (Server)

- PL / SQL data types (Database)

- Ubuntu iptables prevent IP attacks (Linux)

- Analysis of Java reflection mechanism (Programming)

- CentOS 6.4 under PXE + Kickstart unattended operating system installation (Programming)

- Experts teach you how to identify the actual functional differences between the firewall (Linux)

- PHP loop reference caused strange problems (Programming)

- 10 really interesting Linux command (Linux)

- Ubuntu System Log Configuration / var / log / messages (Linux)

- To_teach you three strategies to prevent the LAN IP address theft (Linux)

- Oracle bdump file soaring (Database)

- Internet proxy workaround can not be used under Linux YUM (Linux)

- Compile and install GCC 4.8.1 + GDB 7.6.1 + Eclipse in CentOS 6.4 in (Linux)

- To compile and install MySQL 5.7.7 RC under CentOS 7.1 (Database)

- MySQL optimization resulting order by using filesort (Database)

- Linux use glibc2 library and crypt () function to generate the user password (Programming)

- The Zabbix2.4.5 source compiler installation under Ubuntu 14.04 (Server)

- Python implementation Bursa transition model (Programming)

- On Android running ClojureScript (Linux)

- Setup Qt development environment under Linux (Linux)

 
         
  Java method to read and write files summary
     
  Add Date : 2018-11-21      
         
         
         
  Java method to read and write files to believe that there are many useful at work, including myself before now read and write files using Java methods to deal with aspects of data input and output, really convenient. But since my memory was undoubtedly anxious, since a lot of time will not remember how to write, but my Java code amount it is pitiful, so it should be a lot of practice. Here to do a summary, together aspects of future viewing.

Java read file

package Linux commune;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;

public class JavaIO {
    
    / **
    * The use of the underlying operating system default encoding, GBK and other non-UTF8
    * * /
    
    / **
    * Bytes to read file contents, often used to read binary files, such as pictures, video, sound and other documents
    * * /
    public static void readFileByBytes (String filename) {
        File file = new File (filename);
        FileInputStream in = null;
        try {
            System.out.println ( "bytes read files, read one byte:");
            in = new FileInputStream (file);
            int temp = 0;
            while ((temp = in.read ())! = -1) {
                System.out.println (temp);
            }
            in.close ();
        } Catch (IOException e) {
            e.printStackTrace ();
            return;
        }
        try {
            System.out.println ( "bytes read files, read multiple bytes:");
            byte [] temp = new byte [100];
            int byteread = 0;
            in = new FileInputStream (file);
            JavaIO.showAvailableBytes (in);
            while ((byteread = in.read (temp))! = -1) {
                System.out.write (temp, 0, byteread);
            }
        } Catch (Exception e1) {
            e1.printStackTrace ();
        } Finally {
            if (in! = null) {
                try {
                    in.close ();
                } Catch (IOException e1) {
                    
                }
            }
        }
    }
    / **
    * File in characters reads the file, commonly used for reading text, numbers and other types of
    * * /
    public static void readFileByChar (String filename) {
        File file = new File (filename);
        Reader reader = null;
        try {
            System.out.println ( "in characters reads the file contents, one byte:");
            // InputStreamReader class: byte character conversion to bridge
            reader = new InputStreamReader (new FileInputStream (file));
            int temp;
            while ((temp = reader.read ())! = -1) {
                if (((char) temp)! = '\ r') {
                    System.out.println ((char) temp);
                }
            }
            reader.close ();
        } Catch (Exception e) {
            e.printStackTrace ();
        }
        try {
            System.out.println ( "in characters reads the file contents, read multiple bytes:");
            char [] temp = new char [30];
            int charread = 0;
            reader = new InputStreamReader (new FileInputStream (filename));
            while ((charread = reader.read (temp))! = -1) {
                if ((charread == temp.length) && (temp [temp.length-1]! = '\ r')) {
                    System.out.println (temp);
                } Else {
                    for (int i = 0; i                         if (temp [i] == '\ r') {
                            break;
                        } Else {
                            System.out.println (temp [i]);
                        }
                    }
                }
            }
        } Catch (Exception e) {
            e.printStackTrace ();
        } Finally {
            if (reader! = null) {
                try {
                    reader.close ();
                } Catch (IOException e) {
                    
                }
            }
        }
    }
    / **
    * Read the file in units, commonly used for reading row-oriented format file
    * * /
    public static void readFileByLine (String filename) {
        File file = new File (filename);
        BufferedReader reader = null;
        try {
            System.out.println ( "read the contents of the file in units, once read a whole line:");
            reader = new BufferedReader (new FileReader (file));
            String temp = null;
            int line = 1;
            while ((temp = reader.readLine ())! = null) {
                System.out.println ( "line" + line + ":" + temp);
                line ++;
            }
            reader.close ();
        } Catch (IOException e) {
            e.printStackTrace ();
        } Finally {
            if (reader! = null) {
                try {
                    reader.close ();
                } Catch (IOException e) {
                    
                }
            }
        }
    }
    / **
    * Random read the file contents
    * * /
    public static void readFileByRandomAccess (String filename) {
        RandomAccessFile randomfile = null;
        try {
            System.out.println ( "read some random contents of the file");
            randomfile = new RandomAccessFile (filename, "r");
            long fileLength = randomfile.length ();
            int beginIndex = (fileLength> 4 4:? 0);
            randomfile.seek (beginIndex);
            byte [] bytes = new byte [10];
            int byteread = 0;
            while ((byteread = randomfile.read (bytes))! = -1) {
                System.out.write (bytes, 0, byteread);
            }
        } Catch (IOException e) {
            e.printStackTrace ();
        } Finally {
            if (randomfile! = null) {
                try {
                    randomfile.close ();
                } Catch (IOException e) {
                    
                }
            }
        }
    }
    private static void showAvailableBytes (InputStream in) {
        try {
            System.out.println ( "The current number of bytes in the input stream of bytes is:" + in.available ());
        } Catch (IOException e) {
            e.printStackTrace ();
        }
    }
    public static void main (String [] args) {
        String filename = "E: \\ BaiYiShaoNian.txt";
        JavaIO.readFileByBytes (filename);
        JavaIO.readFileByChar (filename);
        JavaIO.readFileByLine (filename);
        JavaIO.readFileByRandomAccess (filename);
    }
}

Java write file

package Linux commune;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class JavaIO2 {

    public static void main (String [] args) throws IOException {
        String Path = "E: \\ Linux commune \\ JAVA";
        File file = new File ( "E: \\ Linux commune \\ JAVA", "BaiYiShaoNian.txt");
        if (! file.exists ()) {
            try {
                file.createNewFile ();
            } Catch (IOException e) {
                e.printStackTrace ();
            }
        }
        / **
        * Java are three ways to write the file
        * * /
        FileOutputStream fos = null;
        BufferedWriter bw = null;
        FileWriter fw = null;
        int value = 1000;
        
        try {
            fos = new FileOutputStream (new File (Path + "fos.txt"));
            long begin = System.currentTimeMillis ();
            for (int i = 1; i <= value; i ++) {
                fos.write (5);
            }
            long end = System.currentTimeMillis ();
            System.out.println ( "TheCostTime of FileOutputStream is:" + (end-begin));
            fos.close ();
            
            bw = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (new File (Path + "br.txt")), "UTF8"));
            begin = System.currentTimeMillis ();
            for (int i = 1; i <= value; i ++) {
                bw.write (5);
                bw.newLine ();
            }
            bw.close ();
            end = System.currentTimeMillis ();
            System.out.println ( "TheCostTime of BufferedWriter is:" + (end-begin));
            
            fw = new FileWriter (Path + "fw.txt");
            begin = System.currentTimeMillis ();
            for (int i = 1; i <= value; i ++) {
                fw.write (5);
            }
            fw.close ();
            end = System.currentTimeMillis ();
            System.out.println ( "TheCostTime of FileWriter is:" + (end-begin));
            
            
        } Catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace ();
        } Finally {
            try {
                fos.close (); // FileOutputStream
                bw.close (); // BufferedWriter
                fw.close (); // FileWriter
            } Catch (Exception e) {
                e.printStackTrace ();
            }
        }
        
    }
}
     
         
         
         
  More:      
 
- How to install Docker and basic usage on Ubuntu 15.04 (Server)
- Java data structures - the single linked list LinkedList linear table (Programming)
- 2016, the new Node project Precautions (Programming)
- To install network scanning and packet sniffer tool Nmap 7.00 under ubuntu (Linux)
- Linux excellent text editor (Markdown, LaTeX, MathJax) (Linux)
- Hibernate Performance Optimization of EHCache cache (Programming)
- Linux memory Cache Analysis (Linux)
- Commonly used Linux system camouflage method (Linux)
- CentOS7 complete step to install Hadoop2.7 (Server)
- Oracle TDE transparent data encryption (Database)
- PHP loop reference caused strange problems (Programming)
- DB2 commonly used scripting sort out (Database)
- Linux beginners to develop the seven habits (Linux)
- Online booking shocking information leakage risk, you dare book the tickets online? (Linux)
- Android to determine whether the device to open WIFI, GPRS data connection (Programming)
- Eclipse-4.4 crash problem solving under Debian-7.6 (Linux)
- CentOS build JDK environment (Linux)
- Oracle 10g New Features - Archive Compression (Database)
- Linux --- process handle limit summary (Linux)
- Linux System Getting Started Tutorial: How to automatically set the JAVA_HOME environment variable on Linux (Linux)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.