afrag |
|
|||
記錄學習和成長的歷程 |
日歷
統計
導航常用鏈接留言簿隨筆分類隨筆檔案文章檔案搜索積分與排名
最新評論
閱讀排行榜評論排行榜 |
轉自 開發者的天空
本文中我們來討論在NIO2中怎樣創建文件、讀取文件和寫文件。NIO2提供了多種創建 文件的方法,使得我們在創建文件的時候就可以指定文件的某些初始屬性。例如在支持POSIX的文件系統上指定文件的所有者,訪問權限等。關于文件的屬性, 請看上一篇文章Java SE 7新特性之文件操作(5) - 管理元數據 創建文件 可以調用createFile(FileAttribute<?>)方法創建一個空文件。該方法的參數就是文件的初始屬性。下面的例子是怎樣 在創建文件的時候賦予該文件某些權限的屬性: Path sourceFile =
如
果在調用該方法的時候沒有傳入任何參數,那么創建的文件將具有缺省的文件屬性。下面的代碼創建了一個具有缺省文件屬性的文件:![]() Path newFile = ![]() PosixFileAttributes attrs = Attributes.readPosixFileAttributes(sourceFile); FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(attrs.permissions()); try { file.createFile(attr); } catch (IOException x) { //unable to create the file } Path file =
如
果要創建的文件已經存在,該方法會拋出異常。![]() try { file.createFile(); //Create the empty file with default permissions, etc. } catch (FileAlreadyExists x) { System.err.format("file named %s already exists%n", file); } catch (IOException x) { //Some other sort of failure, such as permissions. System.err.format("createFile error: %s%n", x); } 注意在調用createFile方法時,檢查文件是否存在和創建具有特定的屬性的文件是在同一個原子操作中。 還可以使用newOutputSteam方法來創建文件,在本文的后面我們會講到怎樣使用newOutputStream方法來創建文件。 通過Stream I/O讀文件 我們可以通過newInputStream(OpenOption...)方法打開和讀取文件。這個方法返回一個unbuffered輸入流(input stream),我們可以用它來從文件中讀取字節內容。 Path file =
注
意該方法接受可變個數的參數,參數類型為OpenOption,指定了文件怎樣打開。如果不傳入參數,則使用默認的READ方式打開。READ方式是所有
的實現都支持的方式。有一些實現也支持其他的打開方式。![]() InputStream in = null; try { in = file.newInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException x) { System.err.println(x); } finally { if (in != null) in.close(); } 如果傳入的OpenOption或其組合不正確,會拋出異常。如果程序沒有讀權限或I/O錯誤,也會拋出異常。 Creating and Writing a File by Using Stream I/O 使用Stream I/O來創建和寫文件 我們可以使用newOutputStream方法來創建文件、擴展文件或覆蓋已有文件。這個方法為了寫文件而打開或創建文件,該方法返回一個 unbuffered的輸出流(output stream)。newOutputStream方法有兩種形式:
這兩種形式都接受一組OpenOption作為參數,第二種形式還允許指定初始的文件屬性。這個方法支持的StandardOpenOption有:
如果沒有指定OpenOption,該方法的行為是:如果文件不存在,則創建新文件;如果文件存在,那么截斷它。也就是說缺省的選擇是CREATE和 TRUNCATE_EXISTING選項的組合。 下面的代碼打開一個日志文件,如果文件不存在,則創建一個新文件。如果文件 存在,這將新的內容擴展到文件尾部。 import static java.nio.file.StandardOpenOption.*;
Path logfile = ![]() //Convert the string to a byte array. String s = ![]() byte data[] = s.getBytes(); OutputStream out = null; try { out = new BufferedOutputStream(logfile.newOutputStream(CREATE, APPEND)); ![]() out.write(data, 0, data.length); } catch (IOException x) { System.err.println(x); } finally { if (out != null) { out.flush(); out.close(); } } 使用Channel I/O來讀寫文件 Stream I/O每次讀取一個字符,Channel I/O每次讀取一個緩沖塊的數據。ByteChannel接口提供了基本的讀寫功能。SeekableByteChannel擴展了 ByteChannel并提供了維護一個channel中的位置并改變該位置的能力。SeekableByteChannel還支持截斷文件和查詢文件大 小的功能。 移動到文件中不同的位置,從該位置開始讀或寫的能力使我們可以隨機訪問文件。有兩種形式的 newByteChannel方法可以用來讀或寫文件,這兩種形式和newOutputStream方法一樣。
這兩個方法都允許指定OpenOption,newOutputStream所支持的選擇這里也支持,而且這里還支持另外一個選項READ,因為 SeekableByteChannel既支持讀也支持寫。 如果選項是READ,那么該channel就是為了讀訪問打開。如果選項是WRITE或APPEND,則該channel就是為了寫訪問打開。如果沒有指 定,該channel默認是為了讀打開。 下面的代碼從文件中讀取內容并輸出到控制臺上: SeekableByteChannel sbc = null;
下
面的代碼是為了UNIX或其他支持POSIX的文件系統編寫的。這段代碼創建一個新的日志文件或者擴展原有的日志文件,該日志文件創建時指定了訪問權限
(所有者有讀寫權限,同組用戶只有讀權限,其他用戶沒有讀權限)。
try { sbc = file.newByteChannel(); //Defaults to READ ByteBuffer buf = ByteBuffer.allocate(10); //Read the bytes with the proper encoding for this platform. //If you skip this step, you might see something that looks like Chinese //characters when you expect Latin-style characters. String encoding = System.getProperty("file.encoding"); while (sbc.read(buf) > 0) { buf.rewind(); System.out.print(Charset.forName(encoding).decode(buf)); buf.flip(); } } catch (IOException x) { System.out.println("caught exception: " + x); } finally { if (sbc != null) sbc.close(); } import static java.nio.file.StandardCopyOption.*;
//Create the set of options for appending to the file. Set<OpenOptions> options = new HashSet<OpenOption>(); options.add(APPEND); options.add(CREATE); //Create the custom permissions attribute. Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-r------"); FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms); //Convert the string to a ByetBuffer. String s = ![]() byte data[] = s.getBytes(); ByteBuffer bb = ByteBuffer.wrap(data); SeekableByteChannel sbc = null; try { sbc = file.newByteChannel(options, attr); sbc.write(bb); } catch (IOException x) { System.out.println("exception thrown: " + x); } finally { if (sbc != null) sbc.close(); }
|
![]() |
|
Copyright © afrag | Powered by: 博客園 模板提供:滬江博客 |