1.输入流示例
import java.io.*; public class FileInputStreamTest { public static void main(String[] args) throws IOException { //创建字节输入流 FileInputStream fis = new FileInputStream("FileInputStreamTest.java"); //创建一个长度为1024的“竹筒” byte[] bbuf = new byte[1024]; //用于保存实际读取的字节数 int hasRead = 0; //使用循环来重复“取水”过程 while ((hasRead = fis.read(bbuf)) > 0) { //取出“竹筒”中水滴(字节),将字节数组转换成字符串输入! System.out.print(new String(bbuf, 0, hasRead)); } fis.close(); } }
import java.io.*; public class FileReaderTest { public static void main(String[] args) throws IOException { FileReader fr = null; try { //创建字符输入流 fr = new FileReader("FileReaderTest.java"); //创建一个长度为32的“竹筒” char[] cbuf = new char[32]; //用于保存实际读取的字符数 int hasRead = 0; //使用循环来重复“取水”过程 while ((hasRead = fr.read(cbuf)) > 0 ) { //取出“竹筒”中水滴(字节),将字符数组转换成字符串输入! System.out.print(new String(cbuf , 0 , hasRead)); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { //使用finally块来关闭文件输入流 if (fr != null) { fr.close(); } } } }
2.输入流示例
import java.io.*; public class FileOutputStreamTest { public static void main(String[] args) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; try { //创建字节输入流 fis = new FileInputStream("FileOutputStreamTest.java"); //创建字节输入流 fos = new FileOutputStream("newFile.txt"); byte[] bbuf = new byte[32]; int hasRead = 0; //循环从输入流中取出数据 while ((hasRead = fis.read(bbuf)) > 0) { //每读取一次,即写入文件输出流,读了多少,就写多少。 fos.write(bbuf, 0, hasRead); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { //使用finally块来关闭文件输入流 if (fis != null) { fis.close(); } //使用finally块来关闭文件输出流 if (fos != null) { fos.close(); } } } }
import java.io.*; public class FileReaderTest { public static void main(String[] args) throws IOException { FileReader fr = null; try { //创建字符输入流 fr = new FileReader("FileReaderTest.java"); //创建一个长度为32的“竹筒” char[] cbuf = new char[32]; //用于保存实际读取的字符数 int hasRead = 0; //使用循环来重复“取水”过程 while ((hasRead = fr.read(cbuf)) > 0 ) { //取出“竹筒”中水滴(字节),将字符数组转换成字符串输入! System.out.print(new String(cbuf , 0 , hasRead)); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { //使用finally块来关闭文件输入流 if (fr != null) { fr.close(); } } } }
3.使用输入流读取两个文件内容
import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class InputStreamTest { public boolean compareFiles(Path path1, Path path2) throws NoSuchFileException { if (Files.notExists(path1)) { throw new NoSuchFileException(path1.toString()); } if (Files.notExists(path2)) { throw new NoSuchFileException(path2.toString()); } try { if (Files.size(path1) != Files.size(path2)) { return false; } } catch (IOException e) { e.printStackTrace(); } try (InputStream inputStream1 = Files.newInputStream( path1, StandardOpenOption.READ); InputStream inputStream2 = Files.newInputStream( path2, StandardOpenOption.READ)) { int i1, i2; do { i1 = inputStream1.read(); i2 = inputStream2.read(); if (i1 != i2) { return false; } } while (i1 != -1); return true; } catch (IOException e) { return false; } } public static void main(String[] args) { Path path1 = Paths.get("C:\\Users\\user\\Desktop\\1.txt"); Path path2 = Paths.get("C:\\Users\\user\\Desktop\\2.txt"); InputStreamTest test = new InputStreamTest(); try { if (test.compareFiles(path1, path2)) { System.out.println("Files are identical"); } else { System.out.println("Files are not identical"); } } catch (NoSuchFileException e) { e.printStackTrace(); } // the compareFiles method is not the same as Files.isSameFile try { System.out.println(Files.isSameFile(path1, path2)); } catch (IOException e) { e.printStackTrace(); } } }
4.使用输出流复制文件
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class OutputStreamTest { public void copyFiles(Path originPath, Path destinationPath) throws IOException { if (Files.notExists(originPath) || Files.exists(destinationPath)) { throw new IOException( "Origin file must exist and " + "Destination file must not exist"); } byte[] readData = new byte[1024]; try (InputStream inputStream = Files.newInputStream(originPath, StandardOpenOption.READ); OutputStream outputStream = Files.newOutputStream(destinationPath, StandardOpenOption.CREATE)) { int i = inputStream.read(readData); while (i != -1) { outputStream.write(readData, 0, i); i = inputStream.read(readData); } } catch (IOException e) { throw e; } } public static void main(String[] args) { OutputStreamTest test = new OutputStreamTest(); Path origin = Paths.get("C:\\Users\\user\\Desktop\\1.txt"); Path destination = Paths.get("C:\\Users\\user\\Desktop\\3.txt"); try { test.copyFiles(origin, destination); System.out.println("Copied Successfully"); } catch (IOException e) { e.printStackTrace(); } } }
5.标准输出流
import java.io.*; public class PrintStreamTest { public static void main(String[] args) throws IOException { PrintStream ps = null; try { //创建一个节点输出流:FileOutputStream FileOutputStream fos = new FileOutputStream("test.txt"); //以PrintStream来包装FileOutputStream输出流 ps = new PrintStream(fos); //使用PrintStream执行输出 ps.println("普通字符串"); ps.println(new PrintStreamTest()); } catch (IOException ioe) { ioe.printStackTrace(ps); } finally { ps.close(); } } }
6.利用缓冲字节流复制文件
import java.io.*; public class BufferedStreamDemo { public static void main(String[] args) { try { byte[] data = new byte[1]; File srcFile = new File("BufferedStreamDemo.java"); File desFile = new File("BufferedStreamDemo.java.bak"); BufferedInputStream bufferedInputStream = new BufferedInputStream( new FileInputStream(srcFile)); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream( new FileOutputStream(desFile)); System.out.println("复制文件:" + srcFile.length() + "字节"); while(bufferedInputStream.read(data) != -1) { bufferedOutputStream.write(data); } // 将缓冲区中的数据全部写出 bufferedOutputStream.flush(); // 关闭流 bufferedInputStream.close(); bufferedOutputStream.close(); System.out.println("复制完成"); } catch(IOException e) { e.printStackTrace(); } } }
import java.io.*; public class BufferedStreamDemo { public static void main(String[] args) { try { byte[] data = new byte[1]; File srcFile = new File("BufferedStreamDemo.java"); File desFile = new File("BufferedStreamDemo.java.bak"); BufferedInputStream bufferedInputStream = new BufferedInputStream( new FileInputStream(srcFile)); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream( new FileOutputStream(desFile)); System.out.println("复制文件:" + srcFile.length() + "字节"); while(bufferedInputStream.read(data) != -1) { bufferedOutputStream.write(data); } // 将缓冲区中的数据全部写出 bufferedOutputStream.flush(); // 关闭流 bufferedInputStream.close(); bufferedOutputStream.close(); System.out.println("复制完成"); } catch(IOException e) { e.printStackTrace(); } } }
7.利用缓冲字符流将键盘输入直接保存到文件中
import java.io.*; public class BufferedReaderWriterDemo { public static void main(String[] args) { try { System.out.println("输入文本,键入quit结束"); // 缓冲System.in输入流 BufferedReader bufReader = new BufferedReader( new InputStreamReader(System.in)); // 缓冲FileWriter字符输出流 BufferedWriter bufWriter = new BufferedWriter(new FileWriter("Hello.txt")); String input = null; // 每读一行进行一次写入动作 while(!(input = bufReader.readLine()).equals("quit")) { bufWriter.write(input); // newLine()方法写入与操作系统相依的换行字符 bufWriter.newLine(); } bufReader.close(); bufWriter.close(); } catch(IOException e) { e.printStackTrace(); } } }
8.按分隔符读取字串
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Scanner; public class ScannerDemo { public static void main(String[] args) { try (Scanner scanner = new Scanner(new BufferedReader(new FileReader( "mytext.txt")));) { scanner.useDelimiter("[,|^]"); while (scanner.hasNext()) { System.out.println(scanner.next()); } System.out.println("Done!"); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
9.流的转换
InputStreamReader和OutputStreamWriter可以将字节流转换为字符流
import java.io.*; public class KeyinTest { public static void main(String[] args) { BufferedReader br = null; try { //将Sytem.in对象转换成Reader对象 InputStreamReader reader = new InputStreamReader(System.in); //将普通Reader包装成BufferedReader br = new BufferedReader(reader); String buffer = null; //采用循环方式来一行一行的读取 while ((buffer = br.readLine()) != null) { //如果读取的字符串为"exit",程序退出 if (buffer.equals("exit")) { System.out.println("程序退出……"); System.exit(1); } //打印读取的内容 System.out.println("输入内容为:" + buffer); } } catch (IOException ioe) { ioe.printStackTrace(); } //关闭输入流 finally { try { br.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } }
10.内存流
使用ByteArrayInputStream和ByteArrayOutputStream两个类将Byte数组作为读写源头和目的地
import java.io.*; import java.util.*; public class ByteArrayStreamDemo { public static void main(String[] args) { try { File file = new File("test.txt"); BufferedInputStream bufferedInputStream = new BufferedInputStream( new FileInputStream(file)); ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); byte[] bytes = new byte[10]; // 将文件内容写入位数组流 while(bufferedInputStream.read(bytes) != -1) { arrayOutputStream.write(bytes); } arrayOutputStream.close(); bufferedInputStream.close(); // 以字符方式显示位数组内容 bytes = arrayOutputStream.toByteArray(); for(int i = 0; i < bytes.length; i++) { System.out.print((char) bytes[i]); } System.out.println(); // 让使用者输入位置与字符修改位数组内容 Scanner scanner = new Scanner(System.in); System.out.print("输入修改位置:"); int pos = scanner.nextInt(); System.out.print("输入修改字符:"); // 修改数组中对应的字符 bytes[pos-1] = (byte) scanner.next().charAt(0); // 将位数组内容存回文件 ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); BufferedOutputStream bufOutputStream = new BufferedOutputStream( new FileOutputStream(file)); byte[] tmp = new byte[1]; while(byteArrayInputStream.read(tmp) != -1) bufOutputStream.write(tmp); byteArrayInputStream.close(); bufOutputStream.flush(); bufOutputStream.close(); } catch(IOException e) { e.printStackTrace(); } } }
11.重定向标准输入/输出
System提供了以下方法将其重定向
public static void setOut(PrintStream out);
public static void setIn(InputStream in);
import java.io.*; import java.util.*; public class RedirectIn { public static void main(String[] args) { FileInputStream fis = null; try { fis = new FileInputStream("RedirectIn.java"); //将标准输入重定向到fis输入流 System.setIn(fis); //使用System.in创建Scanner对象,用于获取标准输入 Scanner sc = new Scanner(System.in); //增加下面一行将只把回车作为分隔符 sc.useDelimiter("\n"); //判断是否还有下一个输入项 while (sc.hasNext()) { //输出输入项 System.out.println("键盘输入的内容是:" + sc.next()); } } catch (IOException ex) { ex.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } }
import java.io.*; public class RedirectOut { public static void main(String[] args) { PrintStream ps = null; try { ps = new PrintStream(new FileOutputStream("out.txt")); //将标准输出重定向到ps输出流 System.setOut(ps); //向标准输出输出一个字符串 System.out.println("普通字符串"); //向标准输出输出一个对象 System.out.println(new RedirectOut()); } catch (IOException ex) { ex.printStackTrace(); } finally { if (ps != null) { ps.close(); } } } }