zoukankan      html  css  js  c++  java
  • Java.Io 初步了解

    java.io_总结

    File:(文件操作类)

    定义

    File类是对文件/文件夹本身进行:创建、删除、路径等操作,对文件的具体内容不会操作。

    设置路径

    public File(String pathnamc);
    

    设置文件的完整路径:pathnamc

    • 路径的设置采用String格式的 + 文件分级

    文件创建和删除

    public boolean createNewFile(); // 创建文件,返回boolean值
    public boolean delete(); // 删除文件,返回boolean值
    

    文件状态(是否存在)

    public boolean exists();// 判断文件是否存在
    

    路径分隔符常量

    public static final String separator; // 根据系统环境判断路径分隔符
    

    separator是File类中的成员,会根据系统环境判断返回的路径分隔符

    子目录的创建

    • 获取父路径(当前file文件的父路径)
    public File getParentFile();// 返回File型路径,便于File类的引用操作
    public String getParent();// 返回String型路径数据
    
    • 创建子目录(一级/多级)

    我们首先判断我们需要的路径文件是否存在(是否有该文件或文件夹),如果没有我们就会根据父路径进行子目录的创建。

    判断方法:我们可以利用 File.getparentFile()方法返回路径数据,然后引用File.exists()方法判断路径是否可寻(存在)

    public boolean mkdir();  // 处理创建一级目录
    public boolean mkdirs(); // 处理创建多级目录*
    

    文件信息的操作

    • 获取文件大小
    public long length(); // 返回文件的大小(单位:b)
    
    • 判断目标File是否为文件
    public boolean isFile(); // 文件返回True,文件夹返回False
    
    • 判断目标File是否为文件夹
    public boolean isDirectory(); // 文件夹返回True
    
    • 返回最后的修改时间
    public long lastModified(); // 返回时间数字串
    

    由于程序中都是采用时间数字串,所以可以利用时间格式化改变样式

    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") //格式化
    
    • 列出目录子文件/夹信息
    public String [] list();
    
    • 列出所有目录的子文件/夹信息
    public File [] listFiles();
    

    File:实例

    实现文件的创建、删除

    import java.io.File;
    import java.io.IOException;
    
    public class TestDemo {
    	public static void main(String [] args) throws IOException {
    		// 路径设置:F:demodemo.txt
    		File file = new File("F:" + File.separator + "demo" + File.separator + "demo.txt");
    
    		if (file.getParentFile().exists()) {
    			System.out.println(file.getParent() + "	" + "路径已存在");
    		} else if (!file.getParentFile().exists()) {
    			// 查看父路径不存在则创建路径目录
    			file.getParentFile().mkdirs(); // 不存在则创建目录
    			System.out.println(file.getParent() + "	" + "路径创建成功");
    		} 
    		
    		if (file.exists()) {
    			System.out.println("文件已存在");
    		} else if (file.createNewFile()) { // 创建文件
    			System.out.println("文件创建成功");
    		} else {
    			System.out.println("文件穿件失败");
    		}
    		
    		if (file.exists()) {
    			if (file.delete()) {
    				System.out.println("文件删除成功");
    			} else {
    				System.out.println("文件删除失败");
    			}
    		} else {
    			System.out.println("文件不存在");
    		}
    	}
    }
    

    文件最后修改时间

    public class TestDemo {
    	public static void main(String [] args) throws IOException {
    		File file = new File("F:" + File.separator + 
    				"demo" + File.separator + 
    				"txt" + File.separator +
    				"demo.txt");
    		// SimpleDateFormat 将日期格式化输入
            // new Date()构造转换为标准日期格式
    		System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(file.lastModified())));
    		// 返回结果:2019-07-06 21:21:12
    	}
    }
    

    判断是否为目录

    public class TestDemo {
    	public static void main(String [] args) throws IOException {
    		File file = new File("F:" + File.separator + 
    				"demo" + File.separator + 
    				"txt" + File.separator +
    				"demo.txt");
    		System.out.println("是否是文件" + file.isFile());
    		System.out.println("是否是目录" + file.isDirectory());
    		System.out.println(file.length());
    	}
    }
    

    字节流和字符流

    字节流

    字节输出流:OutputStream

    类结构:

    public abstract class OutputStream
    extends Object 
    implements Closeable,Flusable
    
    • Closeable接口:
    public interface Closeable extends AutoCloseable {
        public void close() throws IOException; // 关闭流的方法
    }
    
    • Flusable接口:
    public interface Flushable {
        public void flush() throws IOException ;// 刷新缓冲区
    }
    

    OutputStream 类中已经实现了(提供)close() 和 flush() 两个方法。

    输出方法

    public abstract void write(int b); // 输出单个字节
    public void write(byte [] b); // 输出全部字节数组b
    public void write(byte [] b , int off , int len); // 输出部分数组
    

    FileOutputStream子类

    public FileOutputStream(File file);//创建或覆盖文件
    public FIleOutputStream(File file,boolean append);
    // 创建或对文件追加内容;append=> True:可追加,False:不可追加
    
    • 实例:输出文件内容
    public class TestDemo {
    	public static void main(String [] args) throws IOException {
    		// 路径设置:F:demodemo.txt
    		File file = new File("F:" + File.separator + "demo" + File.separator + "demo.txt");
    		if(!file.getParentFile().exists()) {
    			file.getParentFile().mkdirs();//创建目录
    		}
    		// 使用OutputStream和FileOutputStream实例化
    		OutputStream out = new FileOutputStream(file);
            /****** 核心区域 *********/
    		String str = "Hello,world!";
    		byte [] data = str.getBytes();//getBytes():String类 => Byte[]
    		out.write(data);
    		out.close();	
            /****** END ******/
    	}
    }
    

    字节输入流:InputStream

    类结构

    public abstract class InputStream
    extends Object
    implements Closeable
    

    输入方法

    public abstract int read; // 读取单个字节
    // 当数据没有可读的内容,返回 -1
    public int read(byte [] b); // 读取全部数据保存在byte数组中
    // 返回读取的数据的长度,数据为空则返回 -1
    public int read(byte[] b , int off , int len);
    
    • 实例:读取文件中的数据
    public class TestDemo {
    	public static void main(String [] args) throws IOException {
    		// 路径设置:F:demodemo.txt
    		File file = new File("F:" + File.separator + "demo" + File.separator + "demo.txt");
    		InputStream in = new FileInputStream(file);
    		byte [] data = new byte[1024];
    		int len = in.read(data);
    		in.close();
    		System.out.println("[" + new String(data,0,len) + "]");
    	}
    }
    
    • 实例:单个字节读取文件中的数据
    public class TestDemo {
    	public static void main(String [] args) throws IOException {
    		// 路径设置:F:demodemo.txt
    		File file = new File("F:" + File.separator + "demo" + File.separator + "demo.txt");
    		InputStream in = new FileInputStream(file);
    		byte [] data = new byte[1024];
    		int foot = 0 ;
    		int temp = 0 ;
    		while((temp = in.read()) != -1) {
    			data[foot ++] = (byte) temp;
    		}
    		in.close();
    		System.out.println("[" + new String(data,0,foot) + "]");
    	}
    }
    

    字符输出流:Writer

    public abstract class Writer
    extends Object
    implements Appendable,Closeable,Flushable
    

    Appendable 接口

    public interface Appendable() {
        public Appendable append(char c);
            // 添加指定字符c
        public Appendable append(CharSequence csq);
        	// 添加指的字符序列 csq
        public Appendable append(CharSequence csq,int start,int end);
        	// 添加指定字符序列的子序列
    }
    

    输出方法

    public void write(char[] cbuf);//输出全部字符数组
    public void write(String str); //输出字符串
    

    FIleWriter

    public FileWriter(File file);
    public FileWriter(File file,boolean append);
    

    字符输入流:Reader

    public abstract class Reader
    extends Object
    implements Readable,Closeable
    

    输入方法

    public int read(char[] cbuf);
    

    字符流输出/输入实例:

    public class TestDemo {
    	public static void main(String [] args) throws IOException {
    		// 路径设置:F:demodemo.txt
    		File file = new File("F:" + File.separator + "demo" + File.separator + "demo.txt");
    		out(file);
    		in(file);
    	}
    	public static void out(File file) throws IOException {
    		Writer out = new FileWriter(file);
    		String str = "Hello,World!";
    		out.write(str);
    		out.close();
    	}
    	public static void in(File file) throws IOException {
    		Reader in = new FileReader(file);
    		char[] data = new char[1024];
    		// 由于FileReader.read(char[] cbuf)接收的数据是char字符,所以要定义char数组接收数据
    		int len = in.read(data);
    		in.close();
    		System.out.println(new String(data,0,len));
    	}
    }
    

    字节流 与 字符流两种的区别

    最大的区别

    • 字节流:直接与终端进行数据交互
    • 字符流:需要经过缓冲进行数据交互

    字符流数据在交互中,数据操作的过程中是存放在 缓冲区 之中,在执行close()关闭字符流时候,会自动清空缓冲区;另外可以使用flush()在不执行close()关闭字符流时可以强制清空缓冲区。

    我们通过字符流的方法方法:字符流可以直接传输String字符串数据,非常便利于中文信息的处理;而字节流可以处理更多的数据类型。

    转换流

    InputStreamReader

    public class InputStreamReader
    extends Reader
    
    • 构造方法
    public InputStreamRead(InputStream in);
    

    将字节流转为字符流数据

    OutputStreamWriter

    public class OutputStreamWriter
    extends Writer
    
    • 构造方法
    public OutputStreamWriter(OutputSTream out)
    

    内存操作流

    字节内存流

    public class ByteArrayInputStream
    extends InputStream
    public class ByteArrayOutputStream
    extends OutputStream
    

    ByteArrayInputStream

    • 构造方法
    public ByteArrayInputStream(byte[] buf)
    

    将需要操作的数据设置到 内存输入流 当中

    ByteArrayOutputStream

    • 构造方法
    public ByteArrayOutputStream()
    

    内存输出流(输出数据)

    toByteArray()

    public byte[] toByteArray()
    

    将所有保存在内存中的字节数据转为字节数组

    案例:

    • 将两个文件在内存中合并输出
    public class TestDemo {
    	public static void main(String [] args) throws IOException {
    		File fileA = new File("F:" + File.separator + "demo" + File.separator + "demo.txt");
    		File fileB = new File("F:" + File.separator + "demo" + File.separator + "data.txt");
    		InputStream inA = new FileInputStream(fileA);
    		InputStream inB = new FileInputStream(fileB);
    		ByteArrayOutputStream output = new ByteArrayOutputStream();// 在内存中开辟一个(内存流)空间
    		int temp = 0 ;
    		while((temp = inA.read()) != -1) { //读取A数据
    			output.write(temp);
    		}
    		while((temp = inB.read()) != -1) { //读取B数据
    			output.write(temp);
    		}
    		// 读取A,B文件结束后,将内存中的所有字节数据转为字节数组
    		byte [] data = output.toByteArray();
    		inA.close();
    		inB.close();
    		output.close();
    		System.out.println(new String(data));
    	}
    }
    

    字符内存流:

    public class CharArrayReader
    extends Reader
    
    public class CharArrayWriter
    extends Writer
    

    打印流

    如果使用OutputStream,输出String字符串数据,就需要将String变为字节数组输出getBytes(),同理boolean也需要变为Byte数据输出……

    package helloworld;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    
    class PrintUtil {
    	private OutputStream out; // 输出依靠 OutputSteam类
    	public PrintUtil(OutputStream out) {
    		this.out = out ; //确定OutputStream的对象是File……或者ByteArray……
    	}
    	public void print(int x) throws IOException {
    		this.print(String.valueOf(x));//将x转为String型
    	}
    	public void print(String x) throws IOException {
    		this.out.write(x.getBytes());
    	}
    	public void print(double x) throws IOException {
    		this.print(String.valueOf(x));//将x转为String型
    	}
    	public void println(int x) throws IOException {
    		this.println(String.valueOf(x));
    	}
    	public void println(String x) throws IOException {
    		this.print(x.concat("
    "));
    		//在String字符串结尾添加字符[concat()]
    	}
    	public void println(double x) throws IOException {
    		this.println(String.valueOf(x));
    	}
    	public void close() throws IOException {//关闭输出流
    		this.out.close();
    	}
    }
    
    public class TestDemo {
    	public static void main(String [] args) throws IOException {
    		// 调用PrintUtil类的构造方法,实例化对象
    		PrintUtil pu = new PrintUtil(
    				new FileOutputStream(
    						new File("F:" 
    									+ File.separator + "demo" 
    									+ File.separator + "demo.txt")));
    		pu.print("Hello,");
    		pu.println("World!");
    		pu.println(1+1);
    		pu.println(1.1+1.1);
    		pu.close();
    	}
    }
    

    PrintUtil类,则是为了方便打印而设计的一个工具类,在类中,我们通过调用print方法,可以将当前的数据转为String后在转为Byte型数据,可以方便我们的数据输出;避免我们在代码编写过程中浪费时间来设计数据类型转换为Byte字节输出。

    字节打印流:PrintStream

    • 继承结构
    java.lang.Object
    	java.io.OutputStream
    		java.io.FileOutputStream
    			java.io.PrintStream
    
    • 构造方法
    PrintStream(OutputStream out)
    
    • 实现
    public class TestDemo {
    	public static void main(String [] args) throws IOException {
    		// 调用PrintStream类的构造方法,实例化对象
    		PrintStream pu = new PrintStream(
    				new FileOutputStream(
    						new File("F:" 
    									+ File.separator + "demo" 
    									+ File.separator + "demo.txt")));
    		pu.print("Hello,");
    		pu.println("World!");
    		pu.println(1+1);
    		pu.println(1.1+1.1);
    		pu.close();
    	}
    }
    

    System.IO的支持

    信息输出

    System.out 是在Java中专门支持屏幕输出信息的操作对象(对象由系统负责实例化

    public class TestDemo {
    	public static void main(String [] args) throws IOException {
    		OutputStream out = System.out;
    		out.write("Hello,World!".getBytes());
    	}
    }
    

    上述程序:通过System.out实例对象,OutputStream out 转为了向屏幕输出

    系统输入

    System.in:键盘输入操作。Java并没有直接提供键盘输入功能;而System类中提供了 in 对象,此对象类型是 IntputStream

    public class TestDemo {
    	public static void main(String [] args) throws IOException {
    		//InputStream in = System.in ; // System.in对象是系统实例化,
    		byte [] data = new byte[1024];
    		int len = System.in.read(data); // 输入数据
    		System.out.println(new String(data,0,len));
    	}
    }
    

    System.out 和 System.in 都是系统实例化的对象,在程序中均是向上转型。

    缓冲操作流

    字符缓冲区流:

    • BufferedReader:字符缓冲输入流
    • BufferedWriter:字符缓冲输出流

    字节缓冲区流:

    • BufferedInputStream:字节缓冲输入流
    • BufferedOutputStream:字节缓冲输出流

    字符缓冲输入流

    BufferedReader构造

    public BufferedReader(Reader in);
    

    读取一行数据

    public String readLine() thows IOException;
    

    可以利用循环,读取多行数据。

    若是利用BufferedReader类来处理System.in操作,是不可直接的;因为System.in是InputStream的类型。

    • InputStream 和 Reader 类之间的转换

    引用:InputStreamReader类

    public class TestDemo {
    	public static void main(String [] args) throws IOException {
    		// System.in 是InputStream的类对象
    		// BufferedReader的构造方法接收的是Reader类对象
    		// 利用InputStreamReader将字节流变为字符流
    		BufferedReader buf = 
    				new BufferedReader
    					(new InputStreamReader(System.in));
    		// 调用readLine()方法接收一行数据,以String数据返回,并且以 
     作为分隔
    		String str = buf.readLine();
    		System.out.println(str);
    	}
    }
    

    BufferedReader类构造接收的数据是 Reader字符流对象;

    利用InputStreamReader类将字节流类对象的Systen.in转为字符流的类对象Reader。

    文件读取

    BufferedReader缓冲输入流不仅仅可以可以从键盘中获得,也可以从文件中获得

    public class TestDemo {
    	public static void main(String [] args) throws IOException {
    		File file = new File("F:" + File.separator + "demo" + File.separator + "demo.txt");
    		if (!file.exists()) {
    			file.mkdirs();
    		}
    		BufferedReader buf = 
    				new BufferedReader
    				// FileReader():实例的为字符流数据,而BufferedReader接收Reader字符流
    					(new FileReader(file));
    		String str = null;
    		while ((str = buf.readLine()) != null) {
    			System.out.println(str);
    		}
    		buf.close();
    	}
    } 
    

    Scanner类:扫描流

    • java.util.Scanner:(JDK 1.5

      • 专门负责解决输入流的操作问题
      public final class Scanner
      extends Object
      implements Iterator<String>
      
    • 构造方法:

    public Scanner(File source)
    public Scanner(InputStream source)
    public Scanner(Readable source)
    public Scanner(ReadableByteChannel source)
    public Scanner(String source)
    
    • 类方法

    判断是否有指定数据:

    public boolean hasNextXxx();
    // 举例:
    public boolean hasNext();//表示有数据
    public boolean hasNextDouble();//表述输入的是小数
    

    取出数据:

    public String nextXxx();
    // 举例:
    public String next();//默认返回字符串
    public double nextDouble();//自动转型返回double数据
    

    除了利用hasNextXxx() 和 nextXxx() 方法判断数据以外,在hasNext() 和 next() 方法中支持使用正则表达式对数据进判断

    public boolean hasNext(regax);
    public String next(regax);
    

    总结:

    在读取数据的时候,综合角度:Scanner类 比 BufferedReader 简单;在发现Scanner无法实现的时候再使用BufferedReader

    • InputStream类的功能不足问题被 Scanner 类解决
    • Reader类的功能不足问题被 BufferedReader 类解决
    • OutputStream类的功能不足问题被 PrintStream 类解决
    • Writer类的功能不足问题被 PrintWrite 类解决
  • 相关阅读:
    hdu 1213 (How Many Tables)(简单的并查集,纯模板)
    Android 开发 -------- 自己定义View 画 五子棋
    POJ 2472 106 miles to Chicago
    android application
    Effective C++:条款39:明智而审慎地使用private继承
    云计算统一办公运营平台服务能力设计方案
    LCA 近期公共祖先 小结
    MFC exe使用C++ dll中的std::string 崩溃
    函数调用堆栈图
    【cocos2d-js官方文档】二十、moduleConfig.json
  • 原文地址:https://www.cnblogs.com/wangyuyang1016/p/11190113.html
Copyright © 2011-2022 走看看