io流写如磁盘

public static void main(String[] args) {

FileOutputStream fop = null;
File file;
String content = "This is the text content";
try {
file = new File("D:/test.txt");//初始化file
fop = new FileOutputStream(file);//初始化输出流
// 若文件不存在,则创建它
if (!file.exists()) {
file.createNewFile();
}
// 获取字节的内容数组
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);//写出到指定路径文件中字节的内容数组
fop.flush();
fop.close();
System.out.println("Done");
} catch (IOException e) { //捕捉异常
e.printStackTrace();
} finally {
try {
if (fop != null) {
fop.close();
}
} catch (IOException e) { //捕捉异常
e.printStackTrace();
}
}
}

 

读取文件的内容

public static void main(String[] args) throws IOException {


// BufferedInputStream(InputStream in)
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
"D:/test.txt"));

// 读取数据
// int by = 0;
// while ((by = bis.read()) != -1) {
// System.out.print((char) by);
// }
// System.out.println("---------");

byte[] bys = new byte[1024];
int len = 0;
while ((len = bis.read(bys)) != -1) {
System.out.print(new String(bys, 0, len));
}

// 释放资源
bis.close();
}

//吧一个文件的内容复制到另一文件里

// BufferedInputStream(InputStream in)
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:/test.txt"));
File file = new File("D:/test2.txt");
FileOutputStream fop = new FileOutputStream(file);
// 若文件不存在,则创建它
if (!file.exists()) {
file.createNewFile();
}

byte[] bys = new byte[1024];

int len = 0;
while ((len = bis.read(bys)) != -1) {
fop.write(bys);// 写入D:/test2.txt
System.out.print(new String(bys, 0, len));
}
fop.close();
// 释放资源
bis.close();
}

posted @ 2018-06-01 16:20  树叶儿  阅读(113)  评论(0编辑  收藏  举报