1.IO 流
根据流向分类:
- 输入流:把数据从输入设备读取到内存中的流
- 输出流:把数据从内存中写出到输出设备的流
根据操作数据单位不同分类:
- 字节流:以字节为单位读写数据的流
- 字符流:以字符为单位(主要操作文本数据)读写数据的流
在 Java 中描述的底层父类(JavaIO 流共涉及 40 多个类,都是从如下 4 个底层父类派生的,由这 4 个类派生出来的子类名称都是以其父类作为子类名后缀,4 个底层父类都已实现 AutoCloseable 接口):
- 字节流
- 字节输入流:InputStream
- 字节输出流:OutputStream
- 字符流
- 字符输入流:Reader
- 字符输出流:Writer
- 读取流
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class Test4 { public static void main(String[] args) throws IOException { //循环单个字节读取 InputStream is = new FileInputStream("D:/aaa/b.txt"); int len; while((len=is.read())!=-1){ System.out.print((char) len); } is.close(); //字节数组读取 InputStream is = new FileInputStream("D:/aaa/b.txt"); byte[] b = new byte[1024]; int len; while((len=is.read(b))!=-1){ //在转换时不能全部转换,而是只转换有效字节len(实际读取到的字节个数) //System.out.println(new String(b,0,1024)); System.out.println(new String(b,0,len)); } is.close(); } }
- 写入流
import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class Test2 { public static void main(String[] args) throws IOException { OutputStream os = new FileOutputStream("D:/aaa/b.txt"); byte[] bytes = "hello world".getBytes(); os.write(bytes); //写出一个换行 os.wirte("\r\n".getBytes()); os.close(); } }
回车符\r 和换行符\n:
- 回车符\r:回到一行的开头,ASCII 为 13
- 换行符\n:下一行,ASCII 为 10
系统中的换行:
- Windows 系统中,每行结尾是
回车+换行
,即\r\n- Unix 系统中,每行结尾只有
换行
,即\n- Mac 系统中,每行结尾是
回车
,即\r。(从 Mac OS x 开始与 Linux 统一)通过
System.getProperty("line.separator")
可以获取操作系统的换行符
2.IO 异常的处理
- JDK7 以前
try{ //创建流 }catch(Exception e){ e.printStackTrace() }finally{ //关闭流 }
- JDK7 的处理
JDK7 提供的
try-with-resources
语句,是异常处理的一大利器,该语句确保了每个资源在语句结束时关闭。try(创建流对象语句){ //读写数据 }catch(Exception e){ e.printStackTrace(); }
声明在
try()
中的类必须实现AutoCloseable
接口,在资源处理完毕时,将自动的调用AutoCloseable
接口中的close
方法,如果没有实现AutoCloseable
接口的类将不能写在try()
中。
public class Demo{ public static void main(String[] args){ try( TestAutoCloseable closeable = new TestAutoCloseable(); ){ int num = 1/0; closeable.test(); }catch(Exception e){ e.printStackTrace(); } } } class TestAutoCloseable implements AutoCloseable{ public void close() throws Exception{ System.out.println("Close方法被调用"); } }
3. 属性集
java.util.Properties
继承于Hashtable
,来表示一个持久的属性集。它使用键值对结构存储数据,每个键其对应的值都是一个字符串。
public Object setProperty(String key,String value)
:保存一对属性值public String getProperty(String key)
:使用此 key 搜索值public Set<String> stringPropertyNames()
:所有键的名称的集合public void load(InputStream inStream)
:从字节输入流中读取键值对public vodi store(OutputStream out,@Nullable String comments)
:将字节输入流写入到一个 Properties 文件中,参数二为一个注释的字符串
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于