迁移学习 简而言之_简而言之Java.io:22个案例研究
遷移學(xué)習(xí) 簡而言之
這篇文章試圖涵蓋java.io中的一整套操作。 與與此主題相關(guān)的其他書籍和博客相比,我的動機是通過案例研究來展示“操作方法”。 曾經(jīng)是Java的學(xué)生,我意識到學(xué)習(xí)一種新的程序語言的最有效方法是通過示例:復(fù)制并粘貼一段代碼,運行它以查看結(jié)果,然后嘗試逐步修改并重新運行它。 。 因此,我認(rèn)為這篇文章會有所幫助。
值得注意的是,本文不會涉及任何與java.nio相關(guān)的內(nèi)容,因為我認(rèn)為這是一個完全不同的主題。
目錄
- 情況0:創(chuàng)建一個新文件
- 情況1:File中的兩個常量
- 情況2:刪除文件
- 情況3:創(chuàng)建目錄
- 情況4:列出給定目錄中的文件和目錄
- 情況5:測試文件是否為文件
- 情況6:寫入RandomAccessFile
- 情況7:將字節(jié)寫入文件
- 情況8:將字節(jié)追加到文件
- 情況9:從文件讀取字節(jié)
- 情況10:復(fù)制文件
- 情況11:將字符寫入文件
- 情況12:從文件中讀取字符
- 情況13:從OutputStream轉(zhuǎn)換為FileWriter
- 情況14:從InputStream轉(zhuǎn)換為FileReader
- 案例15:使用管道
- 情況16:將格式化的字符串寫入文件
- 案例17:重定向“標(biāo)準(zhǔn)” IO
- 情況18:逐行讀取文件
- 案例19:壓縮到一個zip文件
- 案例20:從zip文件中提取
- 情況21:推回字節(jié)
情況0:創(chuàng)建一個新文件
import java.io.File; public class FileOperationTest {public static void main(String[] args) {File f = new File("helloworld.txt");try {f.createNewFile();} catch (Exception e) {e.printStackTrace();}} }輸出: 如果之前沒有“ helloword.txt”,則在工作目錄中創(chuàng)建一個新的空文件。
情況1:File中的兩個常量
import java.io.File; public class FileOperationTest {public static void main(String[] args) {System.out.println(File.separator);System.out.println(File.pathSeparator);} }輸出:
/ :我得到上面的輸出,因為我正在Linux上工作。 如果使用Windows,則輸出應(yīng)為\和; 。 可以看出,出于可移植性和魯棒性的目的,應(yīng)始終建議使用這兩個常量。
情況2:刪除文件
import java.io.File; public class FileOperationTest {public static void main(String[] args) {File f = new File("helloworld.txt");if (f.exists()) {if (!f.delete()) {System.out.println("the file cannot be deleted.");}} else {System.out.println("the file does not exist.");}} }情況3:創(chuàng)建目錄
import java.io.File; public class FileOperationTest {public static void main(String[] args) {File f = new File("hello");f.mkdir();} }情況4:列出給定目錄中的文件和目錄
import java.io.File; public class FileOperationTest {public static void main(String[] args) {File f = new File(".");for (String str : f.list()) {System.out.println(str);}} }輸出:我正在使用Eclipse
.settings .classpath .project src bin文件 。 list()返回一個字符串?dāng)?shù)組。 如果您更喜歡File的數(shù)組,請使用File 。 listFiles() :
import java.io.File; public class FileOperationTest {public static void main(String[] args) {File f = new File(".");for (File subFile : f.listFiles()) {System.out.println(subFile.getName());}} }情況5:測試文件是否為文件
import java.io.File; public class FileOperationTest {public static void main(String[] args) {File f = new File("helloworld.txt");if (f.isFile()) {System.out.println("YES");} else {System.out.println("NO");}} }與File結(jié)合。 listFiles() ,我們可以列出給定目錄及其子目錄中的所有文件。
import java.io.File;public class FileOperationTest {public static void main(String[] args) {File f = new File(".");listFiles(f);}private static void listFiles(File f) {if (f.isFile()) {System.out.println(f.getName());return;}for (File subFile : f.listFiles()) {listFiles(subFile);}} }輸出:與案例4進(jìn)行比較以查看差異
org.eclipse.jdt.core.prefs .classpath .project FileOperationTest.java FileOperationTest.class情況6:寫入RandomAccessFile
import java.io.IOException; import java.io.RandomAccessFile;public class FileOperationTest {public static void main(String[] args)throws IOException {RandomAccessFile file = new RandomAccessFile("helloworld.txt", "rw");file.writeBytes("hello world!");file.writeChar('A');file.writeInt(1);file.writeBoolean(true);file.writeFloat(1.0f);file.writeDouble(1.0);file.close();} }如果使用文本編輯器打開文件,則會發(fā)現(xiàn)亂碼,除了第一個hello world!A (請注意,在“ hello world!”末尾的char A )。 這是因為RandomAccessFile僅在文件中寫入字節(jié)數(shù)組。
情況7:將字節(jié)寫入文件
import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream;public class FileOperationTest {public static void main(String[] args)throws IOException {OutputStream out = new FileOutputStream("helloworld.txt");String str = "hello world!";out.write(str.getBytes());out.close();} }這次您可以看到“你好,世界!” 在文件中。 當(dāng)然,您可以逐字節(jié)寫入OutputStream ,但效果不佳:
import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream;public class FileOperationTest {public static void main(String[] args)throws IOException {OutputStream out = new FileOutputStream("helloworld.txt");String str = "hello world!";for (byte b : str.getBytes()) {out.write(b);}out.close();} }情況8:將字節(jié)追加到文件
import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream;public class FileOperationTest {public static void main(String[] args)throws IOException {OutputStream out = new FileOutputStream("helloworld.txt", true);String str = "hello world!";out.write(str.getBytes());out.close();} }輸出: hello world!hello world!
情況9:從文件讀取字節(jié)
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream;public class FileOperationTest {public static void main(String[] args)throws IOException {InputStream in = new FileInputStream("helloworld.txt");byte[] bs = new byte[1024];int len = -1;while ((len = in.read(bs)) != -1) {System.out.println(new String(bs, 0, len));}in.close();} }InputStream 。 如果到達(dá)文件末尾, read()將返回-1。 否則,它將返回讀入緩沖區(qū)的字節(jié)總數(shù)。
情況10:復(fù)制文件
簡單地結(jié)合案例7和9 ,我們將獲得復(fù)制功能。
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;public class Copy {public static void main(String[] args)throws IOException {if (args.length != 2) {System.out.println("java Copy SOURCE DEST");System.exit(1);}InputStream input = new FileInputStream(args[0]);OutputStream output = new FileOutputStream(args[1]);int len = 0;byte bs[] = new byte[1024];while ((len = input.read(bs)) != -1) {output.write(bs, 0, len);}input.close();output.close();} }情況11:將字符寫入文件
import java.io.FileWriter; import java.io.IOException; import java.io.Writer;public class FileOperationTest {public static void main(String[] args)throws IOException {Writer out = new FileWriter("helloworld.txt");String str = "hello world!";out.write(str);out.close();} }對于上述情況,您將獲得與案例7相同的結(jié)果。 那么區(qū)別是什么呢? FileWriter用于編寫字符流。 它將使用默認(rèn)的字符編碼和默認(rèn)的字節(jié)緩沖區(qū)大小。 換句話說,為方便起見,它是FileOutputStream的包裝器類。 因此,要自己指定這些值,請考慮使用FileOutputStream 。
情況12:從文件中讀取字符
import java.io.FileReader; import java.io.IOException; import java.io.Reader;public class FileOperationTest {public static void main(String[] args)throws IOException {Reader in = new FileReader("helloworld.txt");char cs[] = new char[1024];int len = -1;while ((len = in.read(cs)) != -1) {System.out.println(new String(cs, 0, len));}in.close();} }是否使用字節(jié)流或字符流? 真的要看 兩者都有緩沖區(qū)。 InputStream / OutputStream提供了更大的靈活性,但是會使您的“簡單”程序變得復(fù)雜。 另一方面,FileWriter / FileReader提供了一個整潔的解決方案,但是您失去了控制權(quán)。
情況13:從OutputStream轉(zhuǎn)換為FileWriter
import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer;public class FileOperationTest {public static void main(String[] args)throws IOException {Writer out = new OutputStreamWriter(new FileOutputStream("helloworld.txt"));out.write("hello world!");out.close();} }您可以指定字符集,而不是使用默認(rèn)字符編碼。 例如,
Writer out = new OutputStreamWriter(new FileOutputStream("helloworld.txt"), "utf8");情況14:從InputStream轉(zhuǎn)換為FileReader
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader;public class FileOperationTest {public static void main(String[] args)throws IOException {Reader in = new InputStreamReader(new FileInputStream("helloworld.txt"));char cs[] = new char[1024];int len = -1;while ((len = in.read(cs)) != -1) {System.out.println(new String(cs, 0, len));}in.close();} }案例15:使用管道
以下代碼創(chuàng)建兩個線程,一個生產(chǎn)者在一端將某些內(nèi)容寫入管道,而另一個消費者從另一端從該管道讀取內(nèi)容。 要創(chuàng)建管道,我們需要分別創(chuàng)建PipedInputStream和PipedOutputStream ,并使用output.connect(input)或通過其構(gòu)造函數(shù)進(jìn)行連接。 在此程序中,我有意先啟動Consumer線程,并在啟動Producer線程之前讓整個程序Hibernate1秒。 這將顯示管道確實起作用。 值得注意的是,我關(guān)閉了Producer中的管道,因為“ 寫入流的線程應(yīng)始終在終止之前關(guān)閉OutputStream。 ”如果我們刪除out.close()行,將拋出IOException
java.io.IOException: Write end deadat java.io.PipedInputStream.read(PipedInputStream.java:311)at java.io.PipedInputStream.read(PipedInputStream.java:378)at java.io.InputStream.read(InputStream.java:101)at foo.Consumer.run(FileOperationTest.java:58)at java.lang.Thread.run(Thread.java:701)import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream;public class FileOperationTest {public static void main(String[] args)throws IOException, InterruptedException {PipedInputStream input = new PipedInputStream();PipedOutputStream output = new PipedOutputStream();output.connect(input);Producer producer = new Producer(output);Consumer consumer = new Consumer(input);new Thread(consumer).start();Thread.sleep(1000);new Thread(producer).start();} }class Producer implements Runnable {private final OutputStream out;public Producer(OutputStream out) {this.out = out;}@Overridepublic void run() {String str = "hello world!";try {out.write(str.getBytes());out.flush();out.close();} catch (Exception e) {e.printStackTrace();}} }class Consumer implements Runnable {private final InputStream in;public Consumer(InputStream in) {this.in = in;}@Overridepublic void run() {byte[] bs = new byte[1024];int len = -1;try {while ((len = in.read(bs)) != -1) {System.out.println(new String(bs, 0, len));}} catch (IOException e) {e.printStackTrace();}} }情況16:將格式化的字符串寫入文件
PrintStream添加了一些功能,可以方便地打印各種數(shù)據(jù)值的表示形式。 格式字符串的語法與C幾乎相同。
import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream;public class FileOperationTest {public static void main(String[] args)throws IOException {PrintStream print = new PrintStream(new FileOutputStream("helloworld.txt"));print.printf("%s %s!", "hello", "world");print.close();} }案例17:重定向“標(biāo)準(zhǔn)” IO
在Java中,標(biāo)準(zhǔn)輸出和錯誤輸出均為PrintStream 。 標(biāo)準(zhǔn)輸入是InputStream 。 因此,我們可以自由地重新分配它們。 以下代碼將標(biāo)準(zhǔn)輸出重定向到錯誤輸出。
public class FileOperationTest {public static void main(String[] args) {System.out.println("hello world!");System.setOut(System.err);System.out.println("hello world!");} }輸出:在Eclipse中,紅色文本表示錯誤消息
hello world!hello world!情況18:逐行讀取文件
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException;public class FileOperationTest {public static void main(String[] args)throws IOException {BufferedReader reader = new BufferedReader(new FileReader("helloworld.txt"));String str = null;while ((str = reader.readLine()) != null) {System.out.println(str);}reader.close();} }案例19:壓縮到一個zip文件
import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream;public class FileOperationTest {public static void main(String[] args)throws IOException {ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream("helloworld.zip"));String str = "hello world!";for (int i = 0; i < 3; i++) {zipOut.putNextEntry(new ZipEntry("helloworld" + i + ".txt"));zipOut.write(str.getBytes());zipOut.closeEntry();}zipOut.close();} }上面的代碼創(chuàng)建了一個zip文件,并放置了三個文件,分別名為“ helloworld0.txt”,“ helloworld1.txt”和“ helloworld2.txt”,每個文件都包含內(nèi)容“ hello world!”。
案例20:從zip文件中提取
import java.io.FileInputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream;public class FileOperationTest {public static void main(String[] args)throws IOException {ZipInputStream zipIn = new ZipInputStream(new FileInputStream("helloworld.zip"));ZipEntry entry = null;byte bs[] = new byte[1024];while ((entry = zipIn.getNextEntry()) != null) {// get file nameSystem.out.printf("file: %s content: ", entry.getName());int len = -1;// read current entry to the bufferwhile((len=zipIn.read(bs)) != -1) {System.out.print(new String(bs, 0, len));}System.out.println();}zipIn.close();} }輸出:
file: helloworld0.txt content: hello world! file: helloworld1.txt content: hello world! file: helloworld2.txt content: hello world!情況21:推回字節(jié)
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.PushbackInputStream;public class FileOperationTest {public static void main(String[] args)throws IOException {PushbackInputStream push = new PushbackInputStream(new ByteArrayInputStream("hello, world!".getBytes()));int temp = 0;while ((temp = push.read()) != -1) {if (temp == ',') {push.unread('.');}System.out.print((char) temp);}} }上面的代碼在讀取逗號后按了一個點,因此輸出為
hello,. world!但是,如果您嘗試向后推更多字符,例如push.unread("(...)".getBytes()); ,您將獲得IOException :推回緩沖區(qū)已滿。 這是因為推回緩沖區(qū)的默認(rèn)大小為1。要指定更大的容量,請使用構(gòu)造函數(shù)PushbackInputStream(InputStream in, int size) ,例如
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.PushbackInputStream;public class FileOperationTest {public static void main(String[] args)throws IOException {PushbackInputStream push = new PushbackInputStream(new ByteArrayInputStream("hello, world!".getBytes()), 10);int temp = 0;while ((temp = push.read()) != -1) {if (temp == ',') {push.unread("(...)".getBytes());}System.out.print((char) temp);}} }輸出:
hello,(...) world! 參考: 簡而言之 Java.io:PGuru博客上來自我們JCG合作伙伴 Peng Yifan的 22個案例研究 。翻譯自: https://www.javacodegeeks.com/2013/12/java-io-in-nutshell-22-case-studies.html
遷移學(xué)習(xí) 簡而言之
總結(jié)
以上是生活随笔為你收集整理的迁移学习 简而言之_简而言之Java.io:22个案例研究的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python基础——continute与
- 下一篇: 如何避免Java线程中的死锁?