IO流系列(三)

一:
使用StringWriter和StringReader
可使用相应的StringReader类型从字符数据流中读取信息,可以看到,实现方法和相关的StreamReader类型差不多。其实,StringReader类只不过是通过重写派生的成员来从一段字符数据而不是从一个文件中读取信息,代码如下:
//创建一个StringWriter并把字符写入内存
StringWriter strWriter =new StringWriter();

//从StringWriter读取数据。
StringReader strReader =new StringReader(writer.ToString());

java.io.Reader是一个很不错的读取字符流的抽象类,通过继承Reader类,我们可以很方便的读取字符流,比如,我们可以将一个字符串读取为一串串(字符)流,还可以读取一个文件里的内容为一串串的流。

Java(1.6.x)里提供了几种Reader的直接继承类,具体的有:BufferedReader, CharArrayReader, FileReader, InputStreamReader, PipedReader, StringReader等,子类须实现的方法只有 read(char[], int, int) 和 close()。

在这里主要介绍StringReader和FileReader两种。
Private String cmd = "dsfsfsdffssdf";
StringReader sr = new StringReader(cmd);
BufferedReader br = new BufferedReader(sr);

File file = new File("D:/test.txt");
Reader r = new FileReader(file);
int dataLen = r.read(buffer);

 

 

 

 

 

 

 



实例:

configuration_param.properties 文件配置:

gliveId.url=http://www.test.shtml

public class ConfigParamUtil {


    public static String pathUrl=ConfigParamUtil.class.getResource("/").getPath()+"configuration_param.properties";
    public static String getVal(String name){
        Properties prop = new Properties();
        InputStream in=null;
        try {
            in =new FileInputStream(pathUrl);
            prop.load(in);
            return prop.getProperty(name);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if(in!=null)
                    in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static void writeData(String key, String value) {
        Properties prop = new Properties();
        InputStream fis = null;
        OutputStream fos = null;
        try {


            File file = new File(pathUrl);
            if (!file.exists())
                file.createNewFile();
            fis = new FileInputStream(file);
            prop.load(fis);
            fis.close();
            fos = new FileOutputStream(file);
            prop.setProperty(key, value);
            prop.store(fos, "Update '" + key + "' value");
            fos.close();


        } catch (Exception e) {


        }
        finally{
            try {
                if(fos!=null)
                fos.close();
                if(fis!=null)
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tony168hongweigan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值