package com.sevenpad;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.net.URL;
public class demo_io {
int len = 0;// 保存图片字符数组的长度
public static void main(String[] args) {
demo_io demo = new demo_io();
// 创建指定文本在指定位置
demo.m2("d:\\y.txt", demo.m1("d:\\1.txt"));
demo.m1("d:\\y.txt");
// 创建指定图片在指定位置
demo.m4("d:\\y.png", demo.m3("d:\\qq.png"));
// 根据url网址创建图片
demo.m4("d:\\yi.png",
demo.m5("http://avatar.csdn.net/7/3/8/1_nat_myron.jpg"));
}
// 读取文本内容,用FileReader
public String m1(String filePath) {
String result = null;
try {
File file = new File(filePath);
FileReader fr = new FileReader(file);
char[] arr = new char[1024];
len = fr.read(arr);
result = new String(arr, 0, len);
fr.close();
System.out.println("读取文本成功");
System.out.println(len + "---" + result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
// 写文本内容,用FileReader
public void m2(String filePath, String s) {
try {
File file = new File(filePath);
FileWriter fr = new FileWriter(file);
fr.write(s);
fr.close();
System.out.println("写入文本成功");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 读取图片文件,并返回字符数组,用FileInputStream
public byte[] m3(String filePath) {
byte[] arr = null;
try {
File file = new File(filePath);
FileInputStream fr = new FileInputStream(file);
arr = new byte[1024 * 1024];
len = fr.read(arr);
// int i = new int();
fr.close();
System.out.println("图片读取成功");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return arr;
}
// 根据字符数组创建新的图片,用FileOutputStream
public void m4(String filePath, byte[] b) {
try {
File file = new File(filePath);
FileOutputStream fr = new FileOutputStream(file);
fr.write(b, 0, len);
// fr.write(b);
fr.close();
System.out.println("图片创建成功");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 获取指定网址的图片,返回其byte[]
public byte[] m5(String strUrl) {
byte[] arr = null;
try {
URL url = new URL(strUrl);
InputStream fr = url.openConnection().getInputStream();
arr = new byte[1024 * 1024];
len = fr.read(arr);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return arr;
}
}
学习笔记之java---文件操作之输入输出
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.