Java读写Properties文件及JavaIO中字节流和字符的转换
来源:互联网 发布:c语言程序头文件 编辑:程序博客网 时间:2024/05/17 02:13
读写properties文件
Java读写Properties文件是一个比较常见的需求,一般的做法是将properties文件读到Properties类对象中,通过Properteis对象来操作。下面是一段实例代码:
/** * Read Properties file with ASCII codes only */ public static Properties getProperties(String fileName, String path){ Properties props = new Properties(); InputStream in = null;try {in = new FileInputStream(path + fileName);} catch (FileNotFoundException e1) {System.out.println("Can't find c3p0.properties");} try {props.load(in);in.close();} catch (IOException e) {System.out.println("Can't load c3p0.properties");} return props; }上面的代码是用于读取仅包含ASCII码的properties文件,特点是只用了FileInputStream,而没有像往常一样在外面套个FileReader。下面的代码用于写ASCII编码的properties文件:
/** * */ private void setPassword(String passWord){ Properties props = DBUtil.getC3P0Properties(); FileOutputStream out;try {String path = DBUtil.getFullPath(this.getClass());out = new FileOutputStream(path + "/c3p0.properties" ); props.setProperty("c3p0.password", passWord); props.store(out, "Prevent connect for failed connection"); out.close();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} }
字节流到字符的转换
关于Java I/O的更全面信息,可以参考Developerworks上的这篇文章:http://www.ibm.com/developerworks/cn/java/j-lo-javaio/这里贴一下StreamDecoder中的核心方法,看看StreamDecoder是怎样将Stream转为Character的吧:
private int read0() throws IOException { synchronized (lock) { // Return the leftover char, if there is one if (haveLeftoverChar) { haveLeftoverChar = false; return leftoverChar; } // Convert more bytes char cb[] = new char[2]; int n = read(cb, 0, 2); switch (n) { case -1: return -1; case 2: leftoverChar = cb[1]; haveLeftoverChar = true; // FALL THROUGH case 1: return cb[0]; default: assert false : n; return -1; } } }
从上面的代码可以看出,StreamDecoder每次读入两个byte,然后逐个字节进行解析。
- Java读写Properties文件及JavaIO中字节流和字符的转换
- 【Java】javaIO之带缓冲流的字节流文件读写
- Java中字节流和字符流之间的转换
- JavaIO-字节流和字符流的区别
- 【Java】javaIO之带缓冲流的字符流文件读写
- JavaIO之字符流和字节流
- java中字节流与字符流的读写方式
- JAVA 字节流和字符流度读写的区别
- JAVA 字节流和字符流度读写的区别
- java中字节和字符的转换操作
- java中读写.Properties文件
- java基础:字节流和字符流的转换
- JAVA中的字节流和字符流的转换
- JAVA中的字节流和字符流的转换
- Java中的文件读写字节流,字符流
- JavaIO字节流与字符流的区别详解
- javaIO之文件字节流
- Java Properties文件的读写
- 一个很好的博客
- mvc devexpress TreeView
- 杭电2014
- AS3.0杂记——Dictionary、Object与Array
- 动态规划总结
- Java读写Properties文件及JavaIO中字节流和字符的转换
- RAC 常识
- 黑马程序员————学习日记【14】 【正则表达式】
- ubuntu 10.04 glibc安装
- java 课堂笔记
- 第三方支付潜在的洗钱风险
- java面试宝典
- 组合模式(Composite)
- 小米手机连接Ubuntu调试