JAVA多种方式读取文件

package com.file;

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.Reader;

public class TextReadFile {

    /*

     * 一字节为单位读取

     */

    public static void readFileByBytes(String fileName){

        File file = new File(fileName);     //创建文件

        InputStream in = null;

        

        System.out.println("!.以字节为单位读取文件内容:一次读取一个");

        try {

            in = new FileInputStream(file);

            int tempbyte;

            while((tempbyte = in.read())!=-1){

                System.out.write(tempbyte);

            }

            in.close();

        } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

            return;

        }

        

        System.out.println("2.以字节为单位读取文件内容:一次读取多个字节:");

        try {

            byte[] temptypes = new byte[1024];

            int byteread = 0;

            

            in = new FileInputStream(fileName);

            TextReadFile.showAvailableBytes(in);

            while((byteread = in.read(temptypes))!=-1){

                System.out.write(temptypes, 0, byteread);

            }

            

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }finally{

            if(in != null){

                try {

                    in.close();

                } catch (IOException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

            }

        }

    }

    /*

     * 显示输入六中还剩的字节数

     */

    public static void showAvailableBytes(InputStream in){

        try {

            System.out.println("当前字节输入流中的字节数为:"+in.available());

        } catch (IOException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

    /*

     * 义字符为单位读取

     */

    public static void readFileByChar(String fileName){

        File file = new File(fileName);

        Reader read = null;

        

        System.out.println("3、以字符为单位读取文件内容,一次读一个字节:");

        try {

            read = new InputStreamReader(new FileInputStream(file));

            int tempchar;

            while((tempchar= read.read())!=-1){

                if((char)tempchar!=‘r‘){

                    System.out.print((char)tempchar);

                }

            }

            read.close();

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

        

        System.out.println("4.一字符为单位读取文件内容,一次读取多个:");

        char[] tempchars = new char[1024];

        int charread = 0;

        try {

            read = new InputStreamReader(new FileInputStream(file));

            while((charread=read.read(tempchars))!=-1){

                if((charread == tempchars.length)&&(tempchars[tempchars.length-1]!=‘r‘)){

                    System.out.print(tempchars);

                }else{

                    for(int i = 0;i<charread;i++){

                        if(tempchars[i]==‘r‘){

                            continue;

                        }else{

                            System.out.print(tempchars[i]);

                        }

                    }

                }

            }

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }finally{

            if(read != null){

                try {

                    read.close();

                } catch (IOException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

            }

        }

        

    }

    /*

     * 读一行

     */

    public static void readFileByLine(String fileName){

        File file = new File(fileName);

        BufferedReader reader = null;

        

        System.out.println("6.以行为为单位读取文件内容,一次读一行:");

        

        try {

            reader = new BufferedReader(new FileReader(file));

            String tempString = null;

            int line = 1;

            while((tempString = reader.readLine())!=null){

                System.out.println("line"+line+":"+tempString);

                line++;

            }

            reader.close();

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }finally{

            if(reader!= null){

                try {

                    reader.close();

                } catch (IOException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

            }

        }

    }

    public static void main(String[] args) {

        String fileName = "D:/Desktop/JarCode.txt";

        System.out.println("1.按字节为单位读取文件:");

        readFileByBytes(fileName);

        System.out.println("1.按字符为单位读取文件:");

        readFileByChar(fileName);

        System.out.println("1.按行为单位读取文件:");

        readFileByLine(fileName);

    }

}

时间: 2024-10-10 12:06:19

JAVA多种方式读取文件的相关文章

JAVA 以字节流读取文件中的BMP图像

用字节流而不是用JAVA的API函数read()有助于大家理解理解BMP的存储方式哈. 同时,从SQL中读取图片的话,也是用字节流读取,需要自己进行转换的. 顺便保存下代码...下次用就有模板了... 只有24位图的哈.   public Image myRead(String path) throws java.io.IOException {     Image image = null;       int biWidth,biHeight,bicount,biSizeImage,npad

java多线程批量读取文件(七)

新公司入职一个多月了,至今没有事情可以做,十来个新同事都一样抓狂,所以大家都自己学习一些新东西,我最近在看zookeeper,感觉蛮不错的,和微服务的zuul以及eureka功能类似,只是代码复杂了一些.而今天,我所要说的是java多线程读取文件的两个例子: 例子1:java多线程批量读取文件 package face.thread.ReadFile; /** * 多线程读.写文件 *  */import java.io.BufferedReader;import java.io.Buffere

(IO流)java中多种方式读文件,追加文件内容,对文件的各种操作

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.R

Java相对路径读取文件

不管你是新手还是老鸟,在程序中读取资源文件总会遇到一些找不到文件的问题,这与Java底层的实现有关,不能算bug,只要方法得当,问题还是可以解决的. 项目的文件夹结构: repathtest ├─src │    └─com │            └─lavasoft │                    ├─test │                    └─res ├─doc 1.在Java开发工具的project中使用相对路径 在project中,相对路径的根目录是projec

Java配置方式读取外部的资源配置文件

通过@PropertySource可以指定读取的配置文件,通过@Value注解获取值,具体用法: package cn.qlq; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.

java按行读取文件

/** * 按流读取文件 * @param path * @return * @throws FileNotFoundException */ public static BufferedReader openFile(final String path) throws FileNotFoundException { FileInputStream in = new FileInputStream(new File(path)); BufferedReader reader = new Buff

python 之更省内存的方式读取文件

#!/usr/bin/env python # -*- coding: utf-8 -*- #tell() 方法返回文件的当前位置,即文件指针当前位置. #使用with的目的是为里可以自动close掉文件对象 #生成器简单小粒子 def foo1():     yield 1         yield 2     yield 3     yield 4      for i in foo1():     print(i) ''' 如执行:print(foo1()) 调用这个函数的时候,返回的是

java字符流读取文件

package ba; import java.io.*; public class zifuTest { public static void main(String[] args) { FileInputStream fis=null; InputStreamReader reader=null; File f=new File("G:/javakc.txt"); try { fis=new FileInputStream(f); reader=new InputStreamRea

php多种方式获得文件扩展名

/** * * 五种方法获取文件扩展名 **/ $file_name="aa.txt"; echo strrchr($file_name, '.'); echo '<hr/>'; echo substr($file_name, strrpos($file_name, '.')); echo '<hr/>'; $arr=explode('.',$file_name); echo array_pop($arr); echo '<hr/>'; echo p