@nextleaf
2018-08-22T02:12:18.000000Z
字数 15655
阅读 1226
工作日志 Java IO 流

字符流:Reader、Writer
字节流:InputStream、OutputStream
createNewFile()
mkdir()
boolean mkdirs()
exists()
delete()
getName()
getAbsoluteFile() 等
这两类都是用于处理字节流(文件)
这两类都是用于处理字符流(转换流)
这两类都是用于处理字符流(文件)
BufferedWriter(继承于Writer)的write方法:
将给定数组的字符存入此流的缓冲区中,根据需要将缓冲区(默认大小可能是8192字节)的内容刷新到底层流。但是,如果请求的长度≥此缓冲区大小,则此方法将刷新该缓冲区并将各个字符直接写入底层流。
bufferedWriter.write(chars);//将char数组写入缓冲区(如果读取的字符少于数组长度,则以'\u0000'填充。)
BufferedReader(继承于Reader)的read(char[] cbuf,int off,int len)方法:
如果第一次对底层流调用 read返回-1(指示文件末尾,即空文件),则此方法返回-1,否则此方法返回实际读取的字符数。
flush()
将缓冲区的内容写入文件并刷新该流的缓冲区
close()
关闭此流,但会先执行flush()。
通常,处理流套着节点流,节点流里套着文件
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file));
字节流在操作时本身不会用到缓冲区(内存),是文件本身直接操作的,而字符流在操作时使用了缓冲区,通过缓冲区再操作文件。
字节流在操作文件时,即使不关闭资源(close方法),文件也能输出,但是如果字符流不使用close或flush方法的话,则不会输出任何内容。
字符流只能处理字符文件,字节流则可以处理字节文件和字符文件。
■所谓对象序列化就是将对象的状态转换成字节流,保存在文件虫,以后可以通过读取文件再生成相同状态的对象。
■序列化分为两大部分:序列化和反序列化。序列
化是这个过程的第一部分,将数据分解成字节流,
以便存储在文件中或在网络上传输。反序列化就是
打开字节流并重构对象.
Java序列化比较简单,只需实现Java.Io.Serializable接口的类对象就可以转换成字节流或从字节流恢复,不需要在类中增加任何代码。
java.Io包有两个序列化对象的类。
Objectoutputstream负责将对象写入字节流
Objectlnputstream从字节流重构对象。
package com.nl.sx820.io.stream;import java.io.*;/*** Created with IntelliJ IDEA 2018.* Description: FileInputStream 文件拷贝** @author: 黄昭鸿* @date: 2018-08-21* Time: 10:05*/public class FileInputStreamDemo {public static void main(String[] args) {//源文件路径String source = "E:" + File.separator + "Downloads" + File.separator + "a1.png";//目标路径String target = "E:" + File.separator + "Downloads" + File.separator + "a2.png";copyFile(source, target);}public static void copyFile(String src, String target) {/*** Description: 创建文件副本* @author 黄昭鸿* @date 2018/8/21 12:06* @param [src, target]* @return void*///源文件路径File file = new File(src);byte[] bufs = readOldFile(file);//若文件存在if (bufs != null) {System.out.println(aBooleanNewFile(new File(target), file.getName(), bufs));}}public static byte[] readOldFile(File file) {if (file.exists()) {try {byte[] buf;InputStream in = new FileInputStream(file);if (file.isFile()) {buf = new byte[(int) file.length()];in.read(buf);/* byte[] buff=new byte[1024];int temp;while ((temp=in.read(buff))!=-1){outputStream.write(buff);}*///System.out.println(new String(buf));in.close();return buf;} else {in.close();System.out.println("不是文件");return null;}} catch (IOException e) {e.printStackTrace();}} else {System.out.println("路径不存在");}return null;}public static boolean aBooleanNewFile(File newfile, String name, byte[] bytes) {if (newfile.exists()) {if (newfile.isFile()) {System.out.println("覆写");return writefile(newfile, bytes);} else if (newfile.isDirectory()) {newfile = new File(newfile, File.separator + name);System.out.println("新建文件" + newfile.getAbsolutePath());return writefile(newfile, bytes);} else {System.out.println("!");return false;}} else {//file.createNewFile();System.out.println("新建副本" + newfile.getAbsolutePath());return writefile(newfile, bytes);}}public static boolean writefile(File newfile, byte[] bytes) {try {OutputStream outputStream = new FileOutputStream(newfile);outputStream.write(bytes);outputStream.flush();System.out.println("文件已写入");outputStream.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return true;}}
package com.nl.sx820.io.stream;import java.io.*;import java.nio.charset.StandardCharsets;/*** Created with IntelliJ IDEA 2018.* Description: 文件内容读取和写入、字节流和字符流* 字节流与字符流的区别:* 字节流在操作时本身不会用到缓冲区(内存),是文件本身直接操作的,而字符流在操作时使用了缓冲区,通过缓冲区再操作文件。* 字节流在操作文件时,即使不关闭资源(close方法),文件也能输出,但是如果字符流不使用close或flush方法的话,则不会输出任何内容。* 字符流只能处理字符文件,字节流则可以处理字节文件和字符文件* @author: 黄昭鸿* @date: 2018-08-20* Time: 17:52*/public class StreamDemo {public static void main(String[] args) {//转换流,字符流,InputStreamReader、OutputStreamWriterSystem.out.println("-----InputStreamReader、OutputStreamWriter-转换流,字符流---------------");sssssssssss();System.out.println("-------字符流——访问文件---FileReader、FileWriter-------");File file = new File("E:" + File.separator + "Downloads" + File.separator + "nextleafwin.txt");File newFile = new File("E:" + File.separator + "Downloads" + File.separator + "NewNextleafwin.txt");rf(file);//如果文件不存在,FileWriter的write()方法会自动新建文件wf(newFile, "Java.io 包几乎包含了所有操作输入、输出需要的类。所有这些流类代表了输入源和输出目标。一个流可以理解为一个数据的序列。");System.out.println();//字节流:DataInputStream、DataOutputStreamSystem.out.println("------特殊字节流-----DataInputStream、DataOutputStream----------");aVoid();}/*** Description:转换流——字符输入输出流(InputStreamReader、OutputStreamWriter)** @return void* @author 黄昭鸿* @date 2018/8/21 14:20*/private static void sssssssssss() {StringBuffer stringBuffer = new StringBuffer();try {//创建一个输入流对象来读取文件:(还可以使用一个文件对象来创建一个输入流对象来读取文件)InputStream fileInputStream = new FileInputStream("E:" + File.separator + "Downloads" + File.separator + "nextleafwin.txt");//读取到StringBuffer中InputStreamReader reader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);while (reader.ready()) {// 转成char加到StringBuffer对象中stringBuffer.append((char) reader.read());}System.out.println("啦啦啦" + stringBuffer.toString());//也可以/*File file=new File("E:" + File.separator + "Downloads" + File.separator + "nextleafwin.txt");byte[] buf=new byte[(int)file.length()];InputStream in=new FileInputStream(file);in.read(buf);System.out.println(new String(buf));*///关闭读取流reader.close();//关闭输入流,释放系统资源fileInputStream.close();/*这里的代码也可以实现文件读取,但会影响上面的读取流代码,只能选其一使用//从文件输入流一次读取一个字节System.out.println("从文件输入流一次读取一个字节");byte byteData;while ((byteData = (byte) fileInputStream.read()) != -1) {System.out.print((char) byteData);}System.out.println();*/} catch (IOException e) {e.printStackTrace();}//使用字符串类型的文件名来创建一个输出流对象(也可以使用一个文件对象来创建一个输出流来写文件)try {//BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("your output file path"));//如果文件不存在会自动新建OutputStream fileOutputStream = new FileOutputStream("E:" + File.separator + "Downloads" + File.separator + "新nextleafwin.txt");//默认为操作系统默认编码,windows上是gbkOutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8);//使用line.separator系统变量来换行,如下String lineSeparator = System.getProperty("line.separator");fileOutputStream.write(lineSeparator.getBytes());//字符串转为字节数组,写入filefileOutputStream.write("字符串转为字节数组".getBytes());// 写入到缓冲区writer.append("中文输入");writer.append(stringBuffer);//System.out.println(stringBuffer);//换行writer.append("\r\n");// 刷新缓存冲,写入到文件,直接close也会写入writer.flush();// 关闭写入流,同时会把缓冲区内容写入文件writer.close();// 关闭输出流,释放系统资源fileOutputStream.close();} catch (IOException e) {e.printStackTrace();}}//文件内容读取public static void rf(File file) {if (file.isFile()) {try {// 创建 FileReader 对象FileReader fileReader = new FileReader(file);System.out.println("读取的内容为:");/* byte byteData;while ((byteData = (byte) fileReader.read()) != -1) {System.out.print((char) byteData);}System.out.println();*/char[] a = new char[(int) file.length()];// 读取数组中的内容fileReader.read(a);for (char c : a) {System.out.print(c);}fileReader.close();} catch (IOException e) {e.printStackTrace();}} else {System.out.println("不是一个文件,读取??");}}//文件内容写入//如果文件不存在,FileWriter的write()方法会自动新建文件public static void wf(File file, String writeString) {try {if (file.exists()) {if (file.isDirectory()) {file = new File(file, File.separator + "aNewFile.txt");file.createNewFile();// creates a FileWriter ObjectFileWriter writer = new FileWriter(file);// 向文件写入内容System.out.println("开始写入到" + file.getAbsolutePath());writer.write(writeString);writer.flush();writer.close();} else if (file.isFile()) {//覆写System.out.println("覆写!");file.createNewFile();FileWriter writer = new FileWriter(file);System.out.println("开始写入到" + file.getAbsolutePath());writer.write(writeString);writer.flush();writer.close();}} else {//新建System.out.println("新建" + file.getAbsolutePath());file.createNewFile();FileWriter writer = new FileWriter(file);writer.write(writeString);writer.flush();writer.close();}} catch (IOException e) {e.printStackTrace();}}public static void writing(File file, String writeString) {FileWriter writer;try {writer = new FileWriter(file);writer.write(writeString);writer.flush();writer.close();} catch (IOException e) {e.printStackTrace();}}//特殊流--字节流(DataInputStream、DataOutputStream)public static void aVoid() {File newfile = new File("E:" + File.separator + "Downloads" + File.separator + "特殊字节流.txt");DataInputStream dataInputStream = null;DataOutputStream dataOutputStream = null;try {dataInputStream = new DataInputStream(new FileInputStream(newfile));dataOutputStream = new DataOutputStream(new FileOutputStream(newfile));//写入Java类型dataOutputStream.writeBoolean(true);dataOutputStream.writeChar('和');dataOutputStream.writeInt(1);dataOutputStream.writeDouble(3.141592653);dataOutputStream.close();//读出文件内容System.out.println(dataInputStream.readBoolean());System.out.println( dataInputStream.readChar());System.out.println(dataInputStream.readInt());System.out.println(dataInputStream.readDouble());dataInputStream.close();} catch (IOException e) {e.printStackTrace();}finally {try {if (dataInputStream!=null){dataInputStream.close();}if (dataOutputStream!=null){dataOutputStream.close();}} catch (IOException e) {e.printStackTrace();}}}}
package com.nl.sx820.io;import java.io.File;import java.io.IOException;/*** Created with IntelliJ IDEA 2018.* Description:文件,File类及其常用方法* 创建目录* 创建文件* 获取文件信息* @author: 黄昭鸿* @date: 2018-08-20* Time: 14:53*/public class FileDemo {public static void main(String[] args) {//创建目录File parent = new File("E:" + File.separator + "Downloads" + File.separator + "java创建的文件夹");parent.mkdir();//创建文件try {new File(parent + File.separator + "通用分隔符(File.separator).txt").createNewFile();} catch (IOException e) {e.printStackTrace();}createNewFileTest();//复制文件//FileInputStreamDemo.copyFile("","");}public static void createNewFileTest() {//在工作中用到通用分隔符File.separatorFile parent2 = new File("E:" + File.separator + "Downloads" + File.separator + "java创建的文件夹2Test" + File.separator + "子文件夹");File child = new File(parent2, "子File.txt");try {if (!parent2.exists()) {//parent.mkdir()只创建一个文件夹,parent.mkdirs()可创建多个文件夹parent2.mkdirs();child.createNewFile();System.out.println("文件目录及文件创建成功");} else {child.createNewFile();System.out.println("文件创建成功");}} catch (IOException e) {e.printStackTrace();}showInfo(parent2);showListFiles(parent2);showInfo(child);showListFiles(child);//1秒后删除//timing(child);//重命名reName(child, "E:\\Downloads\\java创建的文件夹2Test\\子文件夹\\新的名字.txt");}public static void timing(File child) {for (int i = 0; i < 10; i++) {try {//线程休眠Thread.sleep(1600);} catch (InterruptedException e) {e.printStackTrace();}}child.delete();}public static void showInfo(File f) {System.out.println("\n属性:");System.out.println("文件绝对路径:" + f.getAbsolutePath());System.out.println("文件名:" + f.getName());System.out.println("父目录的路径:" + f.getParent());System.out.println("是否时文件夹:" + f.isDirectory());System.out.println("是否时文件:" + f.isFile());System.out.println("文件长度(字节):" + f.length());System.out.println("是否隐藏:" + f.isHidden());System.out.println();}public static void showListFiles(File f) {if (f.exists()) {if (f.isDirectory()) {//System.out.println("包含的文件名列表:");//Console.log(f.list());System.out.println("[" + f.getAbsolutePath() + "]文件列表:");char str = ' ';System.out.println("文件名\t\t\t大小\t\t\t隐藏");for (File file : f.listFiles()) {if (file.isHidden()) {str = '✔';} else {str = ' ';}System.out.println(file.getName() + "\t\t" + file.length() + "字节\t\t" + str);}} else {System.out.println("不是一个目录...");}} else {System.out.println("路径不存在");}}/*** Description:* 重命名** @param file,name* @return boolean* @author 黄昭鸿* @date 2018/8/20 18:30*/public static boolean reName(File file, String name) {if (file.exists()) {if (file.isFile()) {System.out.println("新名:" + name);return file.renameTo(new File(name));} else {System.out.println("不是一个文件");}} else {System.out.println("路径不存在");return false;}return false;}}
package com.nl.sx820.io;import org.junit.Test;import java.io.File;import java.io.FileNotFoundException;import java.io.IOException;import java.io.RandomAccessFile;/*** Created with IntelliJ IDEA 2018.* Description:RandomAccessFile类支持随机访问,既可当作输入流也可当作输出流* 支持从文件任意位置读取和写入** @author: 黄昭鸿* @date: 2018-08-21* Time: 15:16*/public class RandomAccessFileDemo {/*** Description:RandomAccessFile类* 从文件任意位置读取和写入* @author 黄昭鸿* @date 2018/8/21 16:27* @param* @return void*/@Testpublic void test01() {File file = new File("E:" + File.separator + "Downloads" + File.separator + "RandomAccessFile随机访问.mydata");File newfile = new File("E:" + File.separator + "Downloads" + File.separator + "RandomAccessFile2.mydata");RandomAccessFile randomAccessFile = null;RandomAccessFile newRandomAccessFile = null;try {//one of {@code "r"}, {@code "rw"}, {@code "rws"}, or{@code "rwd"}//r:只读,rw:读写randomAccessFile = new RandomAccessFile(file, "r");newRandomAccessFile = new RandomAccessFile(newfile, "rw");//byte[] bytes=new byte[(int) file.length()];byte[] bytes = new byte[20];int len;while ((len = randomAccessFile.read(bytes)) != -1) {//字节数据,写入的开始位置,长度(字节数)newRandomAccessFile.write(bytes, 0, len);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (randomAccessFile != null) {randomAccessFile.close();}if (newRandomAccessFile != null) {newRandomAccessFile.close();}} catch (IOException e) {e.printStackTrace();}}}/*** Description: 从文件任意位置读取和写入** @author 黄昭鸿* @date 2018/8/21 16:26* @param* @return void*/@Testpublic void test02() {File file = new File("E:" + File.separator + "Downloads" + File.separator + "RandomAccessFile随机访问.mydata");RandomAccessFile randomAccessFile = null;try {//one of {@code "r"}, {@code "rw"}, {@code "rws"}, or{@code "rwd"}randomAccessFile = new RandomAccessFile(file, "rw");//将文件记录指针定位到pos位置,0123456...randomAccessFile.seek(4);System.out.println(randomAccessFile.getFilePointer());/*从该文件读取下一行文本。此方法从文件中读取字节,从当前文件指针开始,直到到达行终止符或文件结束。每个字节通过将字符的低位八位的字节值设置为字符,并将字符的高八位设置为零来转换成字符。因此,此方法不支持完整的Unicode字符集。*/String str=randomAccessFile.readLine();System.out.println(randomAccessFile.getFilePointer());randomAccessFile.seek(4);System.out.println(randomAccessFile.getFilePointer());randomAccessFile.write("abcd".getBytes());System.out.println(randomAccessFile.getFilePointer());randomAccessFile.write(str.getBytes());System.out.println(randomAccessFile.getFilePointer());} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (randomAccessFile != null) {randomAccessFile.close();}} catch (IOException e) {e.printStackTrace();}}}}
package com.nl.sx820.io.stream;import org.junit.Test;import java.io.*;/*** Created with IntelliJ IDEA 2018.* Description:字符流 以字符为单位,只可处理字符文件* Reader类和Writer类是所有字符输入流和输出流超类(抽象类),需要定义子类来实例化。** @author: 黄昭鸿* @date: 2018-08-21* Time: 14:15*/public class FileReaderAndFileWriter {@Testpublic void testFileReader() {//只可处理字符文件File file = new File("E:" + File.separator + "Downloads" + File.separator + "testFileReader.txt");FileReader fileReader = null;try {fileReader = new FileReader(file);char[] chars = new char[20];int len;while ((len = fileReader.read(chars)) != -1) {System.out.println(new String(chars, 0, len));}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (fileReader != null) {try {fileReader.close();} catch (IOException e) {e.printStackTrace();}}}}@Testpublic void testBufferedReader() {File sourcefile = new File("E:" + File.separator + "Downloads" + File.separator + "testFileReader.txt");File targetfile = new File("E:" + File.separator + "Downloads" + File.separator + "newFileReader.txt");BufferedReader bufferedReader = null;BufferedWriter bufferedWriter = null;try {bufferedReader = new BufferedReader(new FileReader(sourcefile));bufferedWriter = new BufferedWriter(new FileWriter(targetfile));char[] chars = new char[1024];int len;//read(char[] cbuf,int off,int len)如果第一次对底层流调用 read 返回 -1(指示文件末尾,即空文件),则此方法返回 -1,否则此方法返回实际读取的字符数。while ((len=bufferedReader.read(chars)) != -1) {//write()将给定数组的字符存入此流的缓冲区中,根据需要将缓冲区(默认大小可能是8192字节)的内容刷新到底层流。// 但是,如果请求的长度≥此缓冲区大小,则此方法将刷新该缓冲区并将各个字符直接写入底层流,此处缓冲区指定为1024字节。bufferedWriter.write(chars,0,len);//bufferedWriter.write(chars);将char数组写入缓冲区(如果读取的字符少于数组长度,则以'\u0000'填充。)//flush(),将缓冲区的内容写入文件并刷新该流的缓冲区//bufferedWriter.flush();//close()关闭此流,但会先执行flush()。}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (bufferedReader != null) {bufferedReader.close();}if (bufferedWriter != null) {bufferedWriter.close();}} catch (IOException e) {e.printStackTrace();}}}}