-
First, get a file handle. File File = new file (); File is a handle to the document. There was a network of calls between the two of them. Then you can start making a phone call.
-
This line reads the information of party A: new FileInputStream (file) is now read in memory. Then it needs to be interpreted as something that B can understand.
-
Since you have used FileInputStream (). Then the corresponding need to use InputStreamReader () This method to interpret the memory just loaded in the data
-
After the interpretation is finished to output AH. Of course it's going to be converted into data that the IO can recognize. Then you need to call the byte code read Method BufferedReader (). Use the ReadLine () method of BufferedReader () to read each row of data in the TXT file.
packagecom.campu;importjava.io.BufferedInputStream;import java.io.BufferedReader;importjava.io.File;importjava.io.FileInputStream;importjava.io.InputStreamReader;importjava.io.Reader;/** * @author 码农小江 * H20121012.java * 2012-10-12下午11:40:21 */publicclassH20121012 { /** * 功能:Java读取txt文件的内容 * 步骤:1:先获得文件句柄 * 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取 * 3:读取到输入流后,需要读取生成字节流 * 4:一行一行的输出。readline()。 * 备注:需要考虑的是异常情况 * @param filePath */ publicstaticvoid readTxtFile(String filePath){ try{ String encoding="GBK"; File file=newFile(filePath); if(file.isFile() && file.exists()){ //判断文件是否存在 InputStreamReader read = newInputStreamReader( new FileInputStream(file),encoding);//考虑到编码格式 BufferedReader bufferedReader = newBufferedReader(read); String lineTxt = null; while((lineTxt = bufferedReader.readLine()) != null){ System.out.println(lineTxt); } read.close(); }else{ System.out.println("找不到指定的文件"); } } catch(Exception e) { System.out.println("读取文件内容出错"); e.printStackTrace(); } } publicstaticvoidmain(String argv[]){ String filePath = "L:\\Apache\\htdocs\\res\\20121012.txt";// "res/"; readTxtFile(filePath); } } |
Read characters from local files in Java