Java处理JSON
JSON(JavaScript Object Notation):JS对象标识法。
是一种轻量级的数据交换格式,类似于xml,更小,更快,更容易解析。
接下来看一看json格式的数据长什么样:
{
"scores":[60,70,80],
"name":"Tom",
"age":20
}
//一对大括号括起来,用k-v对形式表示数据,每个数据之间用“,”隔开,最后一个数据后不用加“,”。
JSON数据在java里可以与java bean数据交互,下面看一个demo:
//原始的json数据获取方式
Person p = new Person();//person是一个bean
p.setName("Tom");
p.setAge(20);
p.setScores(Arrays.asList(60,70,80));
//构造JSONObject对象
JSONObject obj = new JSONObject();
//string
obj.put("name", p.getName());
//int
obj.put("age", p.getAge());
//array
obj.put("scores", p.getScores());
//json对象不能put null
//obj.put("sex", null);编译不通过
System.out.println(obj);
System.out.println("name: " + obj.getString("name"));
System.out.println("age: " + obj.getInt("age"));
System.out.println("scores: " + obj.getJSONArray("scores"));
调用Jackson第三方包处理json
ObjectMapper om = new ObjectMapper();
//构造对象
Person p = new Person();
p.setName("Tom");
p.setAge(20);
p.setScores(Arrays.asList(60,70,80));
//java对象解析成一个Json字符串
String jsonStr = om.writeValueAsString(p);
System.out.println(jsonStr);
//从json字符串重构对象
Person p2 = om.readValue(jsonStr, Person.class);
System.out.println(p2.getName());
System.out.println(p2.getAge());
System.out.println(p2.getScores());
//从json字符串重构为JsonNode对象
JsonNode node = om.readTree(jsonStr);
System.out.println(node.get("name").asText()); System.out.println(node.get("age").asText());
System.out.println(node.get("scores"));
//从文件中读取json
static void testJson() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
File json2 = new File("books2.json");
List<Book> books = new ArrayList<>();
books = objectMapper.readValue(json2, new TypeReference<List<Book>>(){});
for (Book book : books) {
System.out.println(book.getAuthor());
System.out.println(book.getTitle());
}
}
java处理XML文件
XML基础概念
XML:eXtensible Markup Language
可扩展标记语言:意义+数据
其标签可以自行定义,具有自我描述性
<Student>
<name>Tom</name>
<age>20</age>
</Student>
XML解析
java解析XML一般有两种办法
树结构解析:
DOM:Document Object Model 文档对象模型,擅长小规模的读/写
流结构解析
SAX:Simple API for XML 流机制解释器(推模式),擅长读
Stax:The Streaming API for XML 流机制解释器(拉模式),擅长读
java图片文件的处理
读取图片与写入图片
比较自适应读取和根据图片格式(迭代器)读取速度的快慢
public class ImageReader {
public static void main(String[] args) throws Exception {
readAndWrite();
readCompare();
}
static void readAndWrite() throws IOException {
BufferedImage image = ImageIO.read(new File("src/main/resources/u=3363295869,2467511306&fm=26&gp=0[2].jpg"));
System.out.println(image.getHeight());
System.out.println(image.getWidth());
ImageIO.write(image,"png",new File("miao.png"));
}
public static void readCompare() throws Exception{
long startTime = System.nanoTime();
BufferedImage image = ImageIO.read(new File("src/main/resources/u=3363295869,2467511306&fm=26&gp=0[2].jpg"));
long endTime = System.nanoTime();
System.out.println((endTime-startTime)/1000000.0 +"ms");
startTime = System.nanoTime();
Iterator<javax.imageio.ImageReader> readers = ImageIO.getImageReadersByFormatName("jpg");
javax.imageio.ImageReader reader = readers.next();
System.out.println(reader.getClass().getName());
ImageInputStream iis = ImageIO.createImageInputStream(new File("src/main/resources/u=3363295869,2467511306&fm=26&gp=0[2].jpg"));
reader.setInput(iis,true);
System.out.println(image.getHeight());
System.out.println(image.getWidth());
endTime = System.nanoTime();
System.out.println((endTime-startTime)/1000000.0 +"ms");
}
}
截取图片的部分生成一个图片
拼接两张图片形成一张图片
/**
* cropImage 将原始图片文件切割一个矩形,并输出到目标图片文件
* @param fromPath 原始图片
* @param toPath 目标图片
* @param x 坐标起点x
* @param y 坐标起点y
* @param width 矩形宽度
* @param height 矩形高度
* @param readImageFormat 原始文件格式
* @param writeImageFormat 目标文件格式
* @throws Exception
*/
public static void cropImage(String fromPath, String toPath, int x, int y, int width, int height, String readImageFormat,
String writeImageFormat) throws Exception {
FileInputStream fis = null;
ImageInputStream iis = null;
try {
// 读取原始图片文件
fis = new FileInputStream(fromPath);
Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(readImageFormat);
ImageReader reader = it.next();
iis = ImageIO.createImageInputStream(fis);
reader.setInput(iis, true);
// 定义一个矩形 并放入切割参数中
ImageReadParam param = reader.getDefaultReadParam();
Rectangle rect = new Rectangle(x, y, width, height);
param.setSourceRegion(rect);
//从源文件读取一个矩形大小的图像
BufferedImage bi = reader.read(0, param);
//写入到目标文件
ImageIO.write(bi, writeImageFormat, new File(toPath));
} finally {
fis.close();
iis.close();
}
}
/**
* 横向拼接两张图片,并写入到目标文件
* 拼接的本质,就是申请一个大的新空间,然后将原始的图片像素点拷贝到新空间,最后保存
* @param firstPath 第一张图片的路径
* @param secondPath 第二张图片的路径
* @param imageFormat 拼接生成图片的格式
* @param toPath 目标图片的路径
*/
public static void combineImagesHorizontally(String firstPath, String secondPath,String imageFormat, String toPath){
try {
//读取第一张图片
File first = new File(firstPath);
BufferedImage imageOne = ImageIO.read(first);
int width1 = imageOne.getWidth();//图片宽度
int height1 = imageOne.getHeight();//图片高度
//从第一张图片中读取RGB
int[] firstRGB = new int[width1*height1];
firstRGB = imageOne.getRGB(0,0,width1,height1,firstRGB,0,width1);
//对第二张图片做同样的处理
File second = new File(secondPath);
BufferedImage imageTwo = ImageIO.read(second);
int width2 = imageTwo.getWidth();
int height2 = imageTwo.getHeight();
int[] secondRGB = new int[width2*height2];
secondRGB = imageTwo.getRGB(0,0,width2,height2,secondRGB,0,width2);
//生成新图片
int height3 = (height1>height2)?height1:height2; //挑选高度大的,作为目标文件的高度
int width3 = width1 + width2; //宽度,两张图片相加
BufferedImage imageNew = new BufferedImage(width3,height3,BufferedImage.TYPE_INT_RGB);
//设置左半部分的RGB 从(0,0) 开始
imageNew.setRGB(0,0,width1,height1,firstRGB,0,width1);
//设置右半部分的RGB 从(width1, 0) 开始
imageNew.setRGB(width1,0,width2,height2,secondRGB,0,width2);
//保存图片
ImageIO.write(imageNew, imageFormat, new File(toPath));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 纵向拼接图片(两张)
* 拼接的本质,就是申请一个大的新空间,然后将原始的图片像素点拷贝到新空间,最后保存
* @param firstPath 读取的第一张图片
* @param secondPath 读取的第二张图片
* @param imageFormat 图片写入格式
* @param toPath 图片写入路径
*/
public static void combineImagesVertically(String firstPath, String secondPath,String imageFormat, String toPath){
try {
//读取第一张图片
File first = new File(firstPath);
BufferedImage imageOne = ImageIO.read(first);
int width1 = imageOne.getWidth();//图片宽度
int height1 = imageOne.getHeight();//图片高度
//从图片中读取RGB
int[] firstRGB = new int[width1*height1];
firstRGB = imageOne.getRGB(0,0,width1,height1,firstRGB,0,width1);
//对第二张图片做相同的处理
File second = new File(secondPath);
BufferedImage imageTwo = ImageIO.read(second);
int width2 = imageTwo.getWidth();
int height2 = imageTwo.getHeight();
int[] secondRGB = new int[width2*height2];
secondRGB = imageTwo.getRGB(0,0,width2,height2,secondRGB,0,width2);
//生成新图片
int width3 = (width1>width2)?width1:width2; //挑选宽度大的,作为目标文件的宽度
int height3 = height1+height2; //高度,两张图片相加
BufferedImage imageNew = new BufferedImage(width3,height3,BufferedImage.TYPE_INT_RGB);
//设置上半部分的RGB 从(0,0) 开始
imageNew.setRGB(0,0,width1,height1,firstRGB,0,width1);
//设置下半部分的RGB 从(0, height1) 开始
imageNew.setRGB(0,height1,width2,height2,secondRGB,0,width2);
//保存图片
ImageIO.write(imageNew, imageFormat, new File(toPath));
} catch (Exception e) {
e.printStackTrace();
}
}