批量读取本地图片转化为流
File file = new File("E://testPics");
File[] files = file.listFiles();
for (File f : files) {
try {
//读取图片转换为流
FileInputStream fis = new FileInputStream(f);
//(ps:此工具方法贴在了下方)
byte[] data = IOUtil.inputStreamToBytes(fis);
String name = f.getName();
String fileType = name.substring(name.lastIndexOf(".") + 1, name.length()).toLowerCase();
//上传至图片服务器(ps:此处可忽略,此文此方法是将图片上传至相应图片服务器后返回的图片url地址)
String picUrl = uploadFile(data, fileType);
//输出流写到本地
writeUrls(picUrl,"E://urls.txt");
} catch ( Exception e) {
logger.warn("读取上传异常",e);
continue;
}
}
批量将获取的文件url写出到本地txt文件
public void writeUrls(String url,String outPath) throws IOException {
File txt = new File(outPath);
url = url + "\r\n";
byte[] bytes = new byte[512];
bytes = url.getBytes();
int length = bytes.length;
FileOutputStream fos = new FileOutputStream(txt,true);
fos.write(bytes, 0, length);
fos.flush();
fos.close();
}
字节流转化位bytes的方法
public static byte[] inputStreamToBytes(InputStream ins){
byte[] data = null;
ByteArrayOutputStream baos = null;
try
{
baos = new ByteArrayOutputStream();
int i = -1;
byte[] buf = new byte[BUFFER_SIZE];
while ((i = ins.read(buf)) != -1)
{
baos.write(buf, 0, i);
}
data = baos.toByteArray();
}
catch (IOException e)
{
//TODO: 错误处理
}
return data;
}