zoukankan      html  css  js  c++  java
  • 通过InputStream访问文件中的数据的四种方法

    //方法一(每次只读取一个字节)
    	public static void getFile() throws IOException {
    		
    		File file = new File("D:\a.txt");
    		
    		FileInputStream fileinputstream = new FileInputStream(file);
    		
    		int data = fileinputstream.read();
    		int data1 = fileinputstream.read();
    		
    		System.out.println("获取的数据"+data1);
    		fileinputstream.close();
    		
    		
    	}
    

      只是输出目标文件的第一个字符,所以说很不实用

    //方法二
    
    public static void getFile2() throws IOException {
    		File file = new File("D:\a.txt");
    		
    		FileInputStream fileInputStream = new FileInputStream(file);
    		
    		for (int i = 0; i <file.length(); i++) {
    	
    			System.out.print((char)fileInputStream.read());
    		}
    		fileInputStream.close();
    	}
    

    通用步骤:

      1.找到目标文件:注意操作的是文件而不是文件夹(切记!!!!!)

      2.建立通道

      3.[创建缓冲区]

      4.读取数据:read()只获取一个字节

      5.释放之原文件

      

    需要不断地运行一个循环内存占用过大

    public static void getFile3() throws IOException {
    		File file = new File("D:\a.txt");
    		
    		FileInputStream fileInputStream = new FileInputStream(file);
    		
    		byte[] b = new byte[(int) file.length()];
    		
    		int count = fileInputStream.read(b);
    		
    		System.out.println(count);
    		
    		System.out.println(new String(b));
    		
    		fileInputStream.close();
    		
    		
    	}
    

      

    	public static void getFile4() throws IOException {
    		
    		File file = new File("D:\java\第十八次课\代码\Day18\src\com\beiwo\File\Demo1.java");                       
    		
    		FileInputStream fileInputStream = new FileInputStream(file);
    		
    		byte[] b = new byte[1024];
    		
    		int count = 0;
    		
    		while ((count = fileInputStream.read(b))!= -1) {
    		System.out.println(new String(b,0,count));
    			
    		}
    		
    		fileInputStream.close();
    	}
    

      终极版

  • 相关阅读:
    OGRE 第一个程序
    C++ 模板
    WTL状态栏出现 'CMultiPaneStatusBarCtrl' : missing storageclass or type specifie错误
    OGRE运行期结构
    WTL头文件中包含的类
    WTL 方式 对话框数据交换(DDX)
    Windows编程--线程的基本知识
    OGRE——OgreMain模块
    php函数call_user_func和call_user_func_array详解
    整合ECShop2.7.2与Discuz!6.0
  • 原文地址:https://www.cnblogs.com/xpqsd/p/6133827.html
Copyright © 2011-2022 走看看