Java回顧之I/O
工作后,使用的技術(shù)隨著項(xiàng)目的變化而變化,時(shí)而C#,時(shí)而Java,當(dāng)然還有其他一些零碎的技術(shù)??傮w而言,C#的使用時(shí)間要更長(zhǎng)一些,其次是 Java。我本身對(duì)語(yǔ)言沒(méi)有什么傾向性,能干活的語(yǔ)言,就是好語(yǔ)言。而且從面向?qū)ο蟮慕嵌葋?lái)看,我覺(jué)得C#和Java對(duì)我來(lái)說(shuō),沒(méi)什么區(qū)別。
這篇文章主要回顧Java中和I/O操作相關(guān)的內(nèi)容,I/O也是編程語(yǔ)言的一個(gè)基礎(chǔ)特性,Java中的I/O分為兩種類(lèi)型,一種是順序讀取,一種是隨機(jī)讀取。
我們先來(lái)看順序讀取,有兩種方式可以進(jìn)行順序讀取,一種是InputStream/OutputStream,它是針對(duì)字節(jié)進(jìn)行操作的輸入輸出流;另外一種是Reader/Writer,它是針對(duì)字符進(jìn)行操作的輸入輸出流。
下面我們畫(huà)出InputStream的結(jié)構(gòu)
- FileInputStream:操作文件,經(jīng)常和BufferedInputStream一起使用
- PipedInputStream:可用于線(xiàn)程間通信
- ObjectInputStream:可用于對(duì)象序列化
- ByteArrayInputStream:用于處理字節(jié)數(shù)組的輸入
- LineNumberInputStream:可輸出當(dāng)前行數(shù),并且可以在程序中進(jìn)行修改
下面是OutputStream的結(jié)構(gòu)
- PrintStream:提供了類(lèi)似print和println的接口去輸出數(shù)據(jù)
下面我們來(lái)看如何使用Stream的方式來(lái)操作輸入輸出
#p#
- 這里的代碼對(duì)異常的處理非常不完整,稍后我們會(huì)給出完整嚴(yán)謹(jǐn)?shù)拇a。
下面我們來(lái)看Reader的結(jié)構(gòu)
這里的Reader基本上和InputStream能夠?qū)?yīng)上。
Writer的結(jié)構(gòu)如下
下面我們來(lái)看一些使用Reader或者Writer的例子
- 使用BufferedReader讀取文件內(nèi)容
- public static String readFile(String file)throws IOException
- {
- BufferedReader br = null;
- StringBuffer sb = new StringBuffer();
- try
- {
- br = new BufferedReader(new FileReader(file));
- String line = null;
- while((line = br.readLine()) != null)
- {
- sb.append(line);
- }
- }
- catch(Exception ex)
- {
- System.out.println("Error occurs during reading " + file);
- }
- finally
- {
- if (br != null) br.close();
- }
- return sb.toString();
- }
- 使用BufferedWriter復(fù)制文件
- public static void copyFile(String file) throws IOException
- {
- BufferedReader br = null;
- BufferedWriter bw = null;
- try
- {
- br = new BufferedReader(new FileReader(file));
- bw = new BufferedWriter(new FileWriter(file + ".bak"));
- String line = null;
- while((line = br.readLine())!= null)
- {
- bw.write(line);
- }
- }
- catch(Exception ex)
- {
- System.out.println("Error occurs during copying " + file);
- }
- finally
- {
- if (br != null) br.close();
- if (bw != null) bw.close();
- }
- }
下面我們來(lái)看如何對(duì)文件進(jìn)行隨機(jī)訪(fǎng)問(wèn),Java中主要使用RandomAccessFile來(lái)對(duì)文件進(jìn)行隨機(jī)操作。
- 創(chuàng)建大小固定的文件
- public static void createFile(String file, int size) throws IOException
- {
- File temp = new File(file);
- RandomAccessFile raf = new RandomAccessFile(temp, "rw");
- raf.setLength(size);
- raf.close();
- }
接下里,我們來(lái)看一些其他的常用操作
- 移動(dòng)文件
- public static boolean moveFile(String sourceFile, String destFile)
- {
- File source = new File(sourceFile);
- if (!source.exists()) throw new RuntimeException("source file does not exist.");
- File dest = new File(destFile);
- if (!(new File(dest.getPath()).exists())) new File(dest.getParent()).mkdirs();
- return source.renameTo(dest);
- }
- 復(fù)制文件
- public static void copyFile(String sourceFile, String destFile) throws IOException
- {
- File source = new File(sourceFile);
- if (!source.exists()) throw new RuntimeException("File does not exist.");
- if (!source.isFile()) throw new RuntimeException("It is not file.");
- if (!source.canRead()) throw new RuntimeException("File cound not be read.");
- File dest = new File(destFile);
- if (dest.exists())
- {
- if (dest.isDirectory()) throw new RuntimeException("Destination is a folder.");
- else
- {
- dest.delete();
- }
- }
- else
- {
- File parentFolder = new File(dest.getParent());
- if (!parentFolder.exists()) parentFolder.mkdirs();
- if (!parentFolder.canWrite()) throw new RuntimeException("Destination can not be written.");
- }
- FileInputStream fis = null;
- FileOutputStream fos = null;
- try
- {
- fis = new FileInputStream(source);
- fos = new FileOutputStream(dest);
- byte[] buffer = new byte[1024];
- int bytesRead = 0;
- while((bytesRead = fis.read(buffer, 0, buffer.length)) != -1)
- {
- fos.write(buffer, 0, bytesRead);
- }
- fos.flush();
- }
- catch(IOException ex)
- {
- System.out.println("Error occurs during copying " + sourceFile);
- }
- finally
- {
- if (fis != null) fis.close();
- if (fos != null) fos.close();
- }
- }
- 復(fù)制文件夾
- public static void copyDir(String sourceDir, String destDir) throws IOException
- {
- File source = new File(sourceDir);
- if (!source.exists()) throw new RuntimeException("Source does not exist.");
- if (!source.canRead()) throw new RuntimeException("Source could not be read.");
- File dest = new File(destDir);
- if (!dest.exists()) dest.mkdirs();
- File[] arrFiles = source.listFiles();
- for(int i = 0; i < arrFiles.length; i++)
- {
- if (arrFiles[i].isFile())
- {
- BufferedReader reader = new BufferedReader(new FileReader(arrFiles[i]));
- BufferedWriter writer = new BufferedWriter(new FileWriter(destDir + "/" + arrFiles[i].getName()));
- String line = null;
- while((line = reader.readLine()) != null) writer.write(line);
- writer.flush();
- reader.close();
- writer.close();
- }
- else
- {
- copyDir(sourceDir + "/" + arrFiles[i].getName(), destDir + "/" + arrFiles[i].getName());
- }
- }
- }
- 刪除文件夾
- public static void del(String filePath)
- {
- File file = new File(filePath);
- if (file == null || !file.exists()) return;
- if (file.isFile())
- {
- file.delete();
- }
- else
- {
- File[] arrFiles = file.listFiles();
- if (arrFiles.length > 0)
- {
- for(int i = 0; i < arrFiles.length; i++)
- {
- del(arrFiles[i].getAbsolutePath());
- }
- }
- file.delete();
- }
- }
- 將大文件切分成多個(gè)小文件
- public static void splitFile(String filePath, long unit) throws IOException
- {
- File file = new File(filePath);
- if (!file.exists()) throw new RuntimeException("file does not exist.");
- long size = file.length();
- if (unit >= size) return;
- int count = size % unit == 0 ? (int)(size/unit) : (int)(size/unit) + 1;
- String newFile = null;
- FileOutputStream fos = null;
- FileInputStream fis =null;
- byte[] buffer = new byte[(int)unit];
- fis = new FileInputStream(file);
- long startPos = 0;
- String countFile = filePath + "_Count";
- PrintWriter writer = new PrintWriter(new FileWriter( new File(countFile)));
- writer.println(filePath + "\t" + size);
- for (int i = 1; i <= count; i++)
- {
- newFile = filePath + "_" + i;
- startPos = (i - 1) * unit;
- System.out.println("Creating " + newFile);
- fos = new FileOutputStream(new File(newFile));
- int bytesRead = fis.read(buffer, 0, buffer.length);
- if (bytesRead != -1)
- {
- fos.write(buffer, 0, bytesRead);
- writer.println(newFile + "\t" + startPos + "\t" + bytesRead);
- }
- fos.flush();
- fos.close();
- System.out.println("StartPos:" + i*unit + "; EndPos:" + (i*unit + bytesRead));
- }
- writer.flush();
- writer.close();
- fis.close();
- }
原文鏈接:http://www.cnblogs.com/wing011203/archive/2013/05/03/3056535.html