熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

java讀取文本文件代碼

2022-06-13   來源: Java核心技術 
java讀取文本文件的方法有很多這個例子主要介紹最簡單最常用的BufferedReader類
  
  完整例子如下
  
  package netchinaunixbloghzmtext;
  
  import javaioBufferedReader;
  
  import javaioFileReader;
  
  import javaioIOException;
  
  public class ReadFile {
  
  private String path;
  
  public ReadFile(String filePath){
  
  path = filePath;
  
  }
  
  public String[] openFile() throws IOException{
  
  FileReader fr = new FileReader(path)
  
  BufferedReader textReader = new BufferedReader(fr)
  
  String[] textData = new String[readLines()];
  
  int i;
  
  for(i=; i < readLines()i++){
  
  textData[i] = textReaderreadLine()
  
  }
  
  textReaderclose()
  
  return textData;
  
  }
  
  int readLines() throws IOException{
  
  FileReader fileToRead = new FileReader(path)
  
  BufferedReader bf = new BufferedReader(fileToRead)
  
  int numberOfLines = ;
  
  @SuppressWarnings(unused
  
  String oneLine;
  
  while((oneLine = bfreadLine()) != null){
  
  numberOfLines++;
  
  }
  
  bfclose()
  
  return numberOfLines;
  
  }
  
  }
  
  package netchinaunixbloghzmtext;
  
  import javaioIOException;
  
  public class FileData {
  
  public static void main(String[] args) throws IOException{
  
  String filePath = C:/texttxt;
  
  try{
  
  ReadFile reader = new ReadFile(filePath)
  
  String[] content = readeropenFile()
  
  int i;
  
  for(i=;i<contentlength;i++){
  
  Systemoutprintln(content[i])
  
  }
  
  }catch(IOException e){
  
  Systemoutprintln(異常信息 + egetMessage())
  
  }
  
  }
  
  }
  
  javaioBufferedReader
  
  The buffer size may be specified or the default size may be used The default is large enough for most purposes
  
  In general each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly such as FileReaders and InputStreamReaders For example
  
  BufferedReader in = new BufferedReader(new FileReader(fooin)) will buffer the input from the specified file Without buffering each invocation of read() or readLine() could cause bytes to be read from the file converted into characters and then returned which can be very inefficient
  
  Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader
  
  javaioFileReader
  
  FileReader is meant for reading streams of characters For reading streams of raw bytes consider using a FileInputStream
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26249.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.