文件读取的方式 流的几种方式

2024-09-04 12:48
文章标签 读取 方式 几种

本文主要是介绍文件读取的方式 流的几种方式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、按字节读取文件内容
2、按字符读取文件内容
3、按行读取文件内容

4、随机读取文件内容 



public   class  ReadFromFile {
    
/**
     * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
     
*/
    
public   static   void  readFileByBytes(String fileName) {
        File file 
=   new  File(fileName);
        InputStream in 
=   null ;
        
try  {
            System.out.println(
" 以字节为单位读取文件内容,一次读一个字节: " );
            
//  一次读一个字节
            in  =   new  FileInputStream(file);
            
int  tempbyte;
            
while  ((tempbyte  =  in.read())  !=   - 1 ) {
                System.out.write(tempbyte);
            }
            in.close();
        } 
catch  (IOException e) {
            e.printStackTrace();
            
return ;
        }
        
try  {
            System.out.println(
" 以字节为单位读取文件内容,一次读多个字节: " );
            
//  一次读多个字节
             byte [] tempbytes  =   new   byte [ 100 ];
            
int  byteread  =   0 ;
            in 
=   new  FileInputStream(fileName);
            ReadFromFile.showAvailableBytes(in);
            
//  读入多个字节到字节数组中,byteread为一次读入的字节数
             while  ((byteread  =  in.read(tempbytes))  !=   - 1 ) {
                System.out.write(tempbytes, 
0 , byteread);
            }
        } 
catch  (Exception e1) {
            e1.printStackTrace();
        } 
finally  {
            
if  (in  !=   null ) {
                
try  {
                    in.close();
                } 
catch  (IOException e1) {
                }
            }
        }
    }

    
/**
     * 以字符为单位读取文件,常用于读文本,数字等类型的文件
     
*/
    
public   static   void  readFileByChars(String fileName) {
        File file 
=   new  File(fileName);
        Reader reader 
=   null ;
        
try  {
            System.out.println(
" 以字符为单位读取文件内容,一次读一个字节: " );
            
//  一次读一个字符
            reader  =   new  InputStreamReader( new  FileInputStream(file));
            
int  tempchar;
            
while  ((tempchar  =  reader.read())  !=   - 1 ) {
                
//  对于windows下,\r\n这两个字符在一起时,表示一个换行。
                
//  但如果这两个字符分开显示时,会换两次行。
                
//  因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
                 if  ((( char ) tempchar)  !=   ' \r ' ) {
                    System.out.print((
char ) tempchar);
                }
            }
            reader.close();
        } 
catch  (Exception e) {
            e.printStackTrace();
        }
        
try  {
            System.out.println(
" 以字符为单位读取文件内容,一次读多个字节: " );
            
//  一次读多个字符
             char [] tempchars  =   new   char [ 30 ];
            
int  charread  =   0 ;
            reader 
=   new  InputStreamReader( new  FileInputStream(fileName));
            
//  读入多个字符到字符数组中,charread为一次读取字符数
             while  ((charread  =  reader.read(tempchars))  !=   - 1 ) {
                
//  同样屏蔽掉\r不显示
                 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 e1) {
            e1.printStackTrace();
        } 
finally  {
            
if  (reader  !=   null ) {
                
try  {
                    reader.close();
                } 
catch  (IOException e1) {
                }
            }
        }
    }

    
/**
     * 以行为单位读取文件,常用于读面向行的格式化文件
     
*/
    
public   static   void  readFileByLines(String fileName) {
        File file 
=   new  File(fileName);
        BufferedReader reader 
=   null ;
        
try  {
            System.out.println(
" 以行为单位读取文件内容,一次读一整行: " );
            reader 
=   new  BufferedReader( new  FileReader(file));
            String tempString 
=   null ;
            
int  line  =   1 ;
            
//  一次读入一行,直到读入null为文件结束
             while  ((tempString  =  reader.readLine())  !=   null ) {
                
//  显示行号
                System.out.println( " line  "   +  line  +   " "   +  tempString);
                line
++ ;
            }
            reader.close();
        } 
catch  (IOException e) {
            e.printStackTrace();
        } 
finally  {
            
if  (reader  !=   null ) {
                
try  {
                    reader.close();
                } 
catch  (IOException e1) {
                }
            }
        }
    }

    
/**
     * 随机读取文件内容
     
*/
    
public   static   void  readFileByRandomAccess(String fileName) {
        RandomAccessFile randomFile 
=   null ;
        
try  {
            System.out.println(
" 随机读取一段文件内容: " );
            
//  打开一个随机访问文件流,按只读方式
            randomFile  =   new  RandomAccessFile(fileName,  " r " );
            
//  文件长度,字节数
             long  fileLength  =  randomFile.length();
            
//  读文件的起始位置
             int  beginIndex  =  (fileLength  >   4 ?   4  :  0 ;
            
//  将读文件的开始位置移到beginIndex位置。
            randomFile.seek(beginIndex);
            
byte [] bytes  =   new   byte [ 10 ];
            
int  byteread  =   0 ;
            
//  一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
            
//  将一次读取的字节数赋给byteread
             while  ((byteread  =  randomFile.read(bytes))  !=   - 1 ) {
                System.out.write(bytes, 
0 , byteread);
            }
        } 
catch  (IOException e) {
            e.printStackTrace();
        } 
finally  {
            
if  (randomFile  !=   null ) {
                
try  {
                    randomFile.close();
                } 
catch  (IOException e1) {
                }
            }
        }
    }

    
/**
     * 显示输入流中还剩的字节数
     
*/
    
private   static   void  showAvailableBytes(InputStream in) {
        
try  {
            System.out.println(
" 当前字节输入流中的字节数为: "   +  in.available());
        } 
catch  (IOException e) {
            e.printStackTrace();
        }
    }

    
public   static   void  main(String[] args) {
        String fileName 
=   " C:/temp/newTemp.txt " ;
        ReadFromFile.readFileByBytes(fileName);
        ReadFromFile.readFileByChars(fileName);
        ReadFromFile.readFileByLines(fileName);
        ReadFromFile.readFileByRandomAccess(fileName);
    }
}
复制代码

5、将内容追加到文件尾部

复制代码
public   class  AppendToFile {
    
/**
     * A方法追加文件:使用RandomAccessFile
     
*/
    
public   static   void  appendMethodA(String fileName, String content) {
        
try  {
            
//  打开一个随机访问文件流,按读写方式
            RandomAccessFile randomFile  =   new  RandomAccessFile(fileName,  " rw " );
            
//  文件长度,字节数
             long  fileLength  =  randomFile.length();
            
// 将写文件指针移到文件尾。
            randomFile.seek(fileLength);
            randomFile.writeBytes(content);
            randomFile.close();
        } 
catch  (IOException e) {
            e.printStackTrace();
        }
    }

    
/**
     * B方法追加文件:使用FileWriter
     
*/
    
public   static   void  appendMethodB(String fileName, String content) {
        
try  {
            
// 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer  =   new  FileWriter(fileName,  true );
            writer.write(content);
            writer.close();
        } 
catch  (IOException e) {
            e.printStackTrace();
        }
    }

    
public   static   void  main(String[] args) {
        String fileName 
=   " C:/temp/newTemp.txt " ;
        String content 
=   " new append! " ;
        
// 按方法A追加文件
        AppendToFile.appendMethodA(fileName, content);
        AppendToFile.appendMethodA(fileName, 
" append end. \n " );
        
// 显示文件内容
        ReadFromFile.readFileByLines(fileName);
        
// 按方法B追加文件
        AppendToFile.appendMethodB(fileName, content);
        AppendToFile.appendMethodB(fileName, 
" append end. \n " );
        
// 显示文件内容
        ReadFromFile.readFileByLines(fileName);
    }
}

这篇关于文件读取的方式 流的几种方式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1136070

相关文章

Python依赖库的几种离线安装方法总结

《Python依赖库的几种离线安装方法总结》:本文主要介绍如何在Python中使用pip工具进行依赖库的安装和管理,包括如何导出和导入依赖包列表、如何下载和安装单个或多个库包及其依赖,以及如何指定... 目录前言一、如何copy一个python环境二、如何下载一个包及其依赖并安装三、如何导出requirem

java两个List的交集,并集方式

《java两个List的交集,并集方式》文章主要介绍了Java中两个List的交集和并集的处理方法,推荐使用Apache的CollectionUtils工具类,因为它简单且不会改变原有集合,同时,文章... 目录Java两个List的交集,并集方法一方法二方法三总结java两个List的交集,并集方法一

Python中如何控制小数点精度与对齐方式

《Python中如何控制小数点精度与对齐方式》在Python编程中,数据输出格式化是一个常见的需求,尤其是在涉及到小数点精度和对齐方式时,下面小编就来为大家介绍一下如何在Python中实现这些功能吧... 目录一、控制小数点精度1. 使用 round() 函数2. 使用字符串格式化二、控制对齐方式1. 使用

Nginx配置系统服务&设置环境变量方式

《Nginx配置系统服务&设置环境变量方式》本文介绍了如何将Nginx配置为系统服务并设置环境变量,以便更方便地对Nginx进行操作,通过配置系统服务,可以使用系统命令来启动、停止或重新加载Nginx... 目录1.Nginx操作问题2.配置系统服android务3.设置环境变量总结1.Nginx操作问题

Python如何实现读取csv文件时忽略文件的编码格式

《Python如何实现读取csv文件时忽略文件的编码格式》我们再日常读取csv文件的时候经常会发现csv文件的格式有多种,所以这篇文章为大家介绍了Python如何实现读取csv文件时忽略文件的编码格式... 目录1、背景介绍2、库的安装3、核心代码4、完整代码1、背景介绍我们再日常读取csv文件的时候经常

Go 1.23中Timer无buffer的实现方式详解

《Go1.23中Timer无buffer的实现方式详解》在Go1.23中,Timer的实现通常是通过time包提供的time.Timer类型来实现的,本文主要介绍了Go1.23中Timer无buff... 目录Timer 的基本实现无缓冲区的实现自定义无缓冲 Timer 实现更复杂的 Timer 实现总结在

nginx upstream六种方式分配小结

《nginxupstream六种方式分配小结》本文主要介绍了nginxupstream六种方式分配小结,包括轮询、加权轮询、IP哈希、公平轮询、URL哈希和备份服务器,具有一定的参考价格,感兴趣的可... 目录1 轮询(默认)2 weight3 ip_hash4 fair(第三方)5 url_hash(第三

linux打包解压命令方式

《linux打包解压命令方式》文章介绍了Linux系统中常用的打包和解压命令,包括tar和zip,使用tar命令可以创建和解压tar格式的归档文件,使用zip命令可以创建和解压zip格式的压缩文件,每... 目录Lijavascriptnux 打包和解压命令打包命令解压命令总结linux 打包和解压命令打

Python中常用的四种取整方式分享

《Python中常用的四种取整方式分享》在数据处理和数值计算中,取整操作是非常常见的需求,Python提供了多种取整方式,本文为大家整理了四种常用的方法,希望对大家有所帮助... 目录引言向零取整(Truncate)向下取整(Floor)向上取整(Ceil)四舍五入(Round)四种取整方式的对比综合示例应

Rust格式化输出方式总结

《Rust格式化输出方式总结》Rust提供了强大的格式化输出功能,通过std::fmt模块和相关的宏来实现,主要的输出宏包括println!和format!,它们支持多种格式化占位符,如{}、{:?}... 目录Rust格式化输出方式基本的格式化输出格式化占位符Format 特性总结Rust格式化输出方式