java基础之IO类

读文件操作

 
    import java.io.FileInputStream;  
    import java.io.IOException;  
    /** 
     * 
     * 
     *       <p> 
     *       JAVA字节流例子-读文件
     *       </p> 
     */  
    public class ReadFile {  
        public static void main(String[] args) {  
            try {  
            // 创建文件输入流对象  
            FileInputStream is = new FileInputStream("TestFile.txt");  
            // 设定读取的字节数  
            int n = 512;  
            byte buffer[] = new byte[n];  
            // 读取输入流  
            while ((is.read(buffer, 0, n) != -1) && (n > 0)) {  
                System.out.print(new String(buffer));  
            }  
            System.out.println();  
            // 关闭输入流  
            is.close();  
            } catch (IOException ioe) {  
            System.out.println(ioe);  
            } catch (Exception e) {  
            System.out.println(e);  
            }  
        }  
    }

写文件操作

    import java.io.FileOutputStream;  
    import java.io.IOException;  
    /** 
     * 
     * 
     *       <p> 
     *       JAVA字节流例子-写文件 
     *       </p> 
     */  
    public class WriteFile {  
        public static void main(String[] args) {  
            try {  
            System.out.print("输入要保存文件的内容:");  
            int count, n = 512;  
            byte buffer[] = new byte[n];  
            // 读取标准输入流  
            count = System.in.read(buffer);  
            // 创建文件输出流对象  
            FileOutputStream os = new FileOutputStream("WriteFile.txt");  
            // 写入输出流  
            os.write(buffer, 0, count);  
            // 关闭输出流  
            os.close();  
            System.out.println("已保存到WriteFile.txt!");  
            } catch (IOException ioe) {  
            System.out.println(ioe);  
            } catch (Exception e) {  
            System.out.println(e);  
            }  
        }  
    }

猜你喜欢

转载自blog.csdn.net/weixin_43146461/article/details/83027569