Java中对文件的读写控制由输入流和输出流来掌控,读取内容使用输入流,写入内容用输出流;根据文件的的数据类型由可以分为字节流和字符流。
字节流:由字节组成,按字节来对文件进行读写操作,适合于二进制文件,对于图像、音频等人不可读的,也不需要读的,这时候用字节流处理
字符流:在字节流的基础上进行编码,也就是需要人读其中的内容时,可以用字符流
InputStream和OutputStream接口为字节流的父类,使用字节流需要使用其子类
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ByteStream {
public static void main(String[] args)throws IOException {
String fisPath ="C:\\WINDOWS\\system.ini";
String fosPath ="c:\\system.txt";
InputStream fis = new FileInputStream(fisPath);
OutputStream fos = new FileOutputStream(fosPath);
byteStream(fis,fos);
fis.close();
fos.close();
}
public static void byteStream(InputStream is, OutputStream os) throws IOException {
int len = -1;
byte[] buf = new byte[1024];
while ((len = is.read(buf)) != -1) {
os.write(buf, 0, len);
}
os.flush();
}
}
Reader和Writer为字符流,只能读写单个字符,为了提高效率可以使用BufferedReader和BufferedWriter,可以读写一行字符
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintStream;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
public class CharacterStream {
public static void main(String[] args) throws Exception {
String destPath = "c:\\sys.peoperties";
String modifiedPropPath ="c:\\modified.properties";
String copyIniPath = "c:\\sys.ini";
PrintStream ps = new PrintStream(destPath);
BufferedReader bufr = new BufferedReader(new FileReader(destPath));
BufferedWriter bufwd = new BufferedWriter(new FileWriter(modifiedPropPath));
BufferedWriter bufw = new BufferedWriter(new FileWriter(copyIniPath));
characterStream(ps, bufwd, bufr,bufw);
}
public static void characterStream(PrintStream ps, BufferedWriter bufwd,BufferedReader bufr,
BufferedWriter bufw) throws Exception {
Properties prop = System.getProperties();
prop.list(ps);
Set<String> set = new TreeSet<String>();
set = prop.stringPropertyNames();
System.out.println(set.toString());
System.out.println("java.runtime.name = "
+ prop.getProperty("java.runtime.name"));
prop.setProperty("java.runtime.name", "JRE");
System.out.println("java.runtime.name = "
+ prop.getProperty("java.runtime.name"));
prop.store(bufwd, IORelative.myStyleTime(System.currentTimeMillis()));
String readAbleStr = null;
while ((readAbleStr = bufr.readLine()) != null) {
bufw.write(readAbleStr);
bufw.newLine();
bufw.flush();
}
bufr.close();
bufw.close();
}
}
问题:使用Properties的list方法时导出系统属性到文件是有部分内容未显示,但修属性之后使用store()方法存储后可以显示全部内容,但是字符经过了转义处理
----------------------
Android、Java开发期待与您交流! ----------------------