在學習java讀取文件之間,應該先了解一下java讀寫文件常用的幾種流,具體看本人博客http://www.cnblogs.com/Zchaowu/p/7353348.html
讀取文件的四種方式:按字節讀取、按字符讀取、按行讀取、隨機讀取
一、按字節讀取
//1.按字節讀寫文件,用FileInputStream、FileOutputStream String path = "D:\\iotest.txt"; File file = new File(path); InputStream in; //每次只讀一個字節 try { System.out.println("以字節為單位,每次讀取一個字節"); in = new FileInputStream(file); int c; while((c=in.read())!=-1){ if(c!=13&&c!=10){ // \n回車的Ascall碼是10 ,\r換行是Ascall碼是13,不現實揮着換行 System.out.println((char)c); } } } catch (FileNotFoundException e) { e.printStackTrace(); } //每次讀多個字節 try { System.out.println("以字節為單位,每次讀取多個字節"); in = new FileInputStream(file); byte[] bytes = new byte[10]; //每次讀是個字節,放到數組里 int c; while((c=in.read(bytes))!=-1){ System.out.println(Arrays.toString(bytes)); } } catch (Exception e) { // TODO: handle exception }
二、按字符讀取
//2.按字符讀取文件,用InputStreamReader,OutputStreamReader Reader reader = null; try {//每次讀取一個字符 System.out.println("以字符為單位讀取文件,每次讀取一個字符"); in = new FileInputStream(file); reader = new InputStreamReader(in); int c; while((c=reader.read())!=-1){ if(c!=13&&c!=10){ // \n回車的Ascall碼是10 ,\r換行是Ascall碼是13,不現實揮着換行 System.out.println((char)c); } } } catch (Exception e) { // TODO: handle exception } try {//每次讀取多個字符 System.out.println("以字符為單位讀取文件,每次讀取一個字符"); in = new FileInputStream(file); reader = new InputStreamReader(in); int c; char[] chars = new char[5]; while((c=reader.read(chars))!=-1){ System.out.println(Arrays.toString(chars)); } } catch (Exception e) { // TODO: handle exception }
三、按行讀取
//3.按行讀取文件 try { System.out.println("按行讀取文件內容"); in = new FileInputStream(file); Reader reader2 = new InputStreamReader(in); BufferedReader bufferedReader = new BufferedReader(reader2); String line; while((line=bufferedReader.readLine())!=null){ System.out.println(line); } bufferedReader.close(); } catch (Exception e) { // TODO: handle exception }
四、隨機讀取
//4.隨機讀取 try { System.out.println("隨機讀取文件"); //以只讀的方式打開文件 RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); //獲取文件長度,單位為字節 long len = randomAccessFile.length(); //文件起始位置 int beginIndex = (len>4)?4:0; //將文件光標定位到文件起始位置 randomAccessFile.seek(beginIndex); byte[] bytes = new byte[5]; int c; while((c=randomAccessFile.read(bytes))!=-1){ System.out.println(Arrays.toString(bytes)); } } catch (Exception e) { // TODO: handle exception }