Content: file reading method, example of reading method, value of buf in read(buf) method, byte stream buffer object - improving reading speed ///
File reading method: fis.read(), fis.read(buf), see the example for details
Example: file read - read file, display
public class FileInputStreamDemo { public static void main(String[] args) { // To ensure that the file must exist before reading. Encapsulate the string path into a File object File file = new File("F:"+File.separator+"eclipse_javaCode"+File.separator+"day22" +File.separator+"src"+File.separator+"demo"+File.separator+"GetMoney.java"); if(!file.exists()){ throw new RuntimeException("文件不存在!"); } // Create a file byte read stream object FileInputStream fis = null ; try { fis = new FileInputStream(file); // first read method, single read // int ch = 0; // while(ch!=-1){ // ch = fis.read(); // System.out.println(ch); // The first method of reading the file, the acsii code is returned successfully, and the failure returns -1 // } // The second reading method, batch read byte [] buf = new byte [1024 ]; int len = 0 ; while ((len = fis.read(buf)) != -1 ){ System.out.println(new String(buf,0,len)); } } catch (IOException e) { } } }
################################################## ###############
Generally do not directly create a byte buffer of the corresponding size. The
buffer size is generally a multiple of bytes, a multiple of 1024
public static void main(String[] args) throws IOException { File file = new File("F:\\eclipse_javaCode\\day21\\src\\day21\\shangxin.txt"); System.out.println(file.length()); // Get the number of bytes in the file FileInputStream fis = new FileInputStream(file); System.out.println(fis.available()); // Get the number of bytes of the file associated with it byte [] buf = new byte [fis.available()]; // Generally, a buffer of the corresponding size will not be created at once, such as high-definition movies, which is troublesome. // Generally created is a multiple of 1024 fis.read(buf); String s = new String(buf); System.out.println(s); fis.close(); }
byte stream - copy text
public static void main(String[] args) throws IOException { FileOutputStream fos = new FileOutputStream("xxx_copy.txt"); FileInputStream fis = new FileInputStream("FileInputStreamDemo.java"); byte[] buf = new byte[1024]; int len = 0; while((len = fis.read(buf))!= -1){ fos.write(buf,0,len); fos.flush(); } fis.close(); fos.close(); }
Buffer object of
byte stream #####byte stream copy text - use buffer object to improve efficiency
private static void copyByBuffer() throws IOException { FileInputStream fis = new FileInputStream("aaaa.txt"); BufferedInputStream bufis = new BufferedInputStream(fis); FileOutputStream fos = new FileOutputStream("aaaa_copy.txt"); BufferedOutputStream bufos = new BufferedOutputStream(fos); byte[] buf = new byte[1024]; int by = 0; while((by = bufis.read(buf))!=-1){ bufos.write(buf,0,by); bufos.flush(); } fos.close(); fis.close(); }