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();
    	}
    

      终极版

  • 相关阅读:
    Vue 创建项目
    Vue组件之间的传参
    Vue自定义组件
    Python开发之路
    爬虫
    手撸系列
    Django从入门到不会放弃
    前端
    day29 TCP的三次握手 TCP的四次挥手 基于TCP的socket
    day28 客户端服务端架构介绍
  • 原文地址:https://www.cnblogs.com/xpqsd/p/6133827.html
Copyright © 2011-2022 走看看