Java基础知识四

字符转数据输入流

import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.Charsets;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class string2Inputstream {
    public static void main(String[] args) {//构造字符串列表
        List<String> names = new LinkedList<String>();
        names.add("Xiaohong");
        names.add("Xiaoming");
        names.add("Daming");
        names.add("Xiaohei");
        //合并为一个字符串,以逗号相连
        String namestr = String.join(",", names);
        //将字符串作为默认的输入流
        InputStream in = IOUtils.toInputStream(namestr, Charsets.toCharset("UTF-8"));

        //重置系统的输入流
        System.setIn(in);
        //模拟键盘输入 这也是0]平台测试用例输入的原理
        // 此处也可以换成一个文件输入流
        Scanner sc=new Scanner(System.in);sc.useDelimiter(",");
        while(sc.hasNext()){
            System.out.println(sc.next());
        }
    }
}
XML解析


-树结构
·DOM: Document Object Model 文档对象模型,擅长(小规模)读/写
流结构·

SAX: Simple API for XML 流机制解释器(推模式),擅长读

Stax: The Streaming APIfor XML, 流机制解释器(拉模式),擅长读JDK6引入

DOM方式

DOM是W3C处理XML的标准API直观易用。
其处理方式是将XML整个作为类似树结构的方式读入内存中以便操作及解析,方便修改。
解析大数据量的XM文件,会遇到内存泄露及程序崩溃的风险。

DocumentBuilder解析类,parse方法
。Node 节点主接口,getChildNodes返回一个NodeList·

NodeList节点列表,每个元素是一个Node
·Document文档根节点
·Element标签节点元素(每一个标签都是标签节点)·

Text节点(包含在XML元素内的,都算Text节点)
Attr节点(每个属性节点)

Simple API for XMI


-采用事件/流模型来解析XML 文档,更快速、更轻量。-有选择的解析和访问,不像DOM 加载整个文档,内存要求较低SAX对XML文档的解析为一次性读取,不创建/不存储文档对象,很难同时访问文档中的多处数据。
推模型。当它每发现一个节点就引发一个事件,而我们需要编写这些事件的处理程序。关键类:DefaultHandler

Streaming API for XMI


-流模型中的拉模型
-在遍历文档时,会把感兴趣的部分从读取器中拉出,不需要引发事件,允许我们选择性地处理节点。这大大提高了灵活性,以及整体效率。
两套处理API
·基于指针的API,XMIStreamReader
·基于迭代器的API,XMLEventReader

第三方库 JDOM  DOM4J.

JSON

和]ava Bean对象进行互解析
-具有一个无参的构造函数
-可以包括多个属性,所有属性都是private
-每个属性都有相应的Getter/Setter方法
-Java Bean用于封装数据,又可称为PO]O(Plain Old Java Object

org.json:JSON官方推荐的解析类-简单易用,通用性强-复杂功能欠缺
GSON:Google出品
-基于反射,可以实现JSON对象、ISON字符串和Java对象互转

Jackson:号称最快的ISON处理器-简单易用,社区更新和发布速度比较快

org.json
{
  "books": [{
    "category": "COOKING",
    "title": "Everyday Italian",
    "author": "Giada De Laurentiis",
    "year": "2085",
    "price": 30.00
  }, {
    "category": "CHILDREN",
    "title": "Harry Potter",
    "author": "﹞ K. Rowling",
    "year": "2005",
    "price": 29.99
  }, {
    "category": "WEB",
    "title": "Learning XML",
    "author": "Erik T. Ray",
    "year": "2003",
    "price": 39.95
  }]
}



import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class OrgJsonTest {
    public static void main(String[] args) {
        testJsonObject();
        System.out.println("=========华丽丽的分割线=====");
        testJsonFile();
    }

    public static void testJsonObject() {
        //构造对象
        Person p = new Person();
        p.setName("Tom");
        p.setAge(20);
        p.setScores(Arrays.asList(60, 70, 80));

        JSONObject obj = new JSONObject();
        obj.put("name", p.getName());
        obj.put("age", p.getAge());
        obj.put("scores", p.getScores());

        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"));
    }

    public static void testJsonFile(){
        File file = new File("book.json");
        try(FileReader reader = new FileReader(file)){
            int fileLen = (int) file.length();
            char[] chars = new char[fileLen];
            reader.read(chars);
            String s= String.valueOf(chars);
            JSONObject jsonObject = new JSONObject(s);

            JSONArray books = jsonObject.getJSONArray("books");
            List<Book> bookList =  new ArrayList<Book>();

            for(Object book : books) {
                JSONObject bookObject =(JSONObject) book;
                Book  book1 = new Book();
                book1.setAuthor(bookObject.getString("author"));
                book1.setYear(bookObject.getString("year"));
                book1.setTitle(bookObject.getString("title"));
                book1.setPrice(bookObject.getInt("price"));
                book1.setCategory(bookObject.getString("category"));
                bookList.add(book1);
            }
            for (Book book : bookList){
                System.out.println(book.getAuthor()+" , "+book.getTitle());
            }

        }catch (Exception ex){
            ex.printStackTrace();
        }

    }
}
package org.example;

import java.util.List;

public class Person {
    private String name;
    private int age;
    private List<Integer> scores;

    public Person() {
    }


    public Person(String name, int age) {
        this.name=name;
        this.age=age;

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public List<Integer> getScores() {
        return scores;
    }

    public void setScores(List<Integer> scores) {
        this.scores = scores;
    }
}
package org.example;

import java.util.List;

public class Book {
    private String category;
    private String title;
    private String author;
    private String year;
    private double price;

    public Book(String category, String title, String author, String year, double price) {
        this.category = category;
        this.title = title;
        this.author = author;
        this.year = year;
        this.price = price;
    }

    public Book() {

    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}
GSON

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.FileReader;
import java.util.Arrays;
import java.util.List;

public class GsonTest {
    public static void main(String[] args) {
        testJsonObject();
        System.out.println("=========华州丽的分割线==========");
        testJsonFile();
    }

    public static void testJsonObject() {
        //构造对象
        Person p = new Person();
        p.setName("Tom");
        p.setAge(20);
        p.setScores(Arrays.asList(60, 70, 80));

        //java对象到字符串
        Gson gson = new Gson();
        String s = gson.toJson(p);
        System.out.println(s);
        //java 字符串到对象
        Person p2 = gson.fromJson(s, Person.class);
        System.out.println(p2.getName());
        System.out.println(p2.getAge());
        System.out.println(p2.getScores());

        //调用GSON 的JsonObject
        JsonObject json = gson.toJsonTree(p).getAsJsonObject();//将整个json解析为一棵树

        System.out.println(json.get("name"));
        System.out.println(json.get("age"));
        System.out.println(json.get("scores"));

    }

    public static void testJsonFile() {
        Gson gson = new Gson();
        File file = new File("book2.json");
        try (FileReader reader = new FileReader(file)) {
            List<Book> books = gson.fromJson(reader, new TypeToken<List<Book>>() {
            }.getType());
            for (Book book : books)
                System.out.println(book.getAuthor() + "," + book.getTitle());
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
}
[{
    "category": "COOKING",
    "title": "Everyday Italian",
    "author": "Giada De Laurentiis",
    "year": "2085",
    "price": 30.00
  }, {
    "category": "CHILDREN",
    "title": "Harry Potter",
    "author": "﹞ K. Rowling",
    "year": "2005",
    "price": 29.99
  }, {
    "category": "WEB",
    "title": "Learning XML",
    "author": "Erik T. Ray",
    "year": "2003",
    "price": 39.95
  }]
jackson
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class JacksonTest {
    public static void main(String[] args) throws IOException {
        testJsonObject();
        System.out.println("=========华州丽的分割线==========");
        testJsonFile();
    }


    public static void testJsonObject() throws JsonProcessingException {
       ObjectMapper om = new ObjectMapper();
        //构造对象
        Person p = new Person();
        p.setName("Tom");
        p.setAge(20);
        p.setScores(Arrays.asList(60, 70, 80));

        //对象解析为字符串
        String jsonStr = om.writeValueAsString(p);
        System.out.println(jsonStr);
        //字符串重构为对象
        Person p2 = om.readValue(jsonStr, Person.class);
        System.out.println(p2.getName());
        System.out.println(p2.getAge());
        System.out.println(p2.getScores());
        //字符串重构node对象
        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"));

    }

    public static void testJsonFile() throws IOException {
        ObjectMapper om = new ObjectMapper();

        File json2 = new File("book2.json");
        List<Book> books = om.readValue(json2, new TypeReference<List<Book>>() {
        });
        for(Book book: books){
            System.out.println(book.getAuthor());
            System.out.println(book.getTitle());
        }

    }
}

JSON是一种独立于编程语言的、轻量的、数据交换格式
·有多种第三方库辅助我们进行ISON生成和解析
·注意:JSON会丢失顺序性

图形 图像

Java原生支持jpg, png, bmp, wbmp, gif

javax.imageio.ImageIO
-自动封装多种ImageReader和ImageWriter,读写图像文件
-read 读取图片write 写图片
java.awt.image.BufferedImage,图像在内存中的表示类

-getHeight 获取高度
-getWidth获取宽度
图像文件读写/截取/合并

package org.example;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;

public class ImageTest {
    public static void main(String[] args) throws Exception {
        readAndWrite();
        readComparison();
        cropImage("c:/temp/ecnu.jpg", "c:/temp/shida.jpg", 750, 250, 700, 300, "jpg", "jpg");
        combineImagesHorizontally("c:/temp/ecnu.jpg", "c:/temp/ecnu.jpg", "jpg", "c:/temp/ecnu2.jpg");
        combineImagesVertically("c:/temp/ecnu.jpg", "c:/temp/ecnu.jpg", "jpg", "c:/temp/ecnu3.jpg");
    }

    public static void readAndWrite() throws Exception {
        BufferedImage image = ImageIO.read(new File("C:/temp/ecnu.jpg"));
        System.out.println("Height:" + image.getHeight());// 高度像素
        System.out.println("width:" + image.getWidth());// 宽度像素
        ImageIO.write(image, "png", new File("c:/temp/ecnu.png"));
    }

    public static void readComparison() throws Exception {
        System.out.println("===========加载速度测试========");
        //mageIo需要测试图片的类型,加载合适的ImageReader来读取图片,耗时更长
        long startTime = System.nanoTime();
        BufferedImage image = ImageIO.read(new File("c:/temp/ecnu.jpg"));
        System.out.println("Height:" + image.getHeight());// 高度像素
        System.out.println("Width:" + image.getWidth());// 宽度像素
        long endTime = System.nanoTime();
        System.out.println((endTime - startTime) / 1000000.0 + "亳秒");

        //指定用jpg Reader来加载,速度会加快
        startTime = System.nanoTime();
        Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("jpg");
        ImageReader reader = (ImageReader) readers.next();
        System.out.println(reader.getClass().getName());
        ImageInputStream iis = ImageIO.createImageInputStream(new File("c:/temp/ecnu.jpg"));
        reader.setInput(iis, true);
        System.out.println("Height:" + reader.getHeight(0));// 高度像素
        System.out.println("Width:" + reader.getWidth(0));// 宽度像素
        endTime = System.nanoTime();
        System.out.println((endTime - startTime) / 1000000.0 + "亳秒");

    }

    /**
     * cropImage 将原始图片文件切割一个矩形,并输出到目标图片文件
     *
     * @param fromPath         原始图片
     * @param toPath           目标图片
     * @param x                坐标起点
     * @param y                坐标起点
     * @param width            矩形宽度
     * @param height           矩形高度
     * @param readImageFormat  原始文件格式
     * @param writeImageFormat 目标文件格式
     */
    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_BGR);

            //设置左半部分的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_BGR);

            //设置左半部分的RGB从(0,0)开始
            imageNew.setRGB(0, 0, width1, height1, firstRGB, 0, width1);
            //设置右半部分的RGB从(width1,0)开始
            imageNew.setRGB(0,height1,width2,height2,secondRGB,0,width2);
            //保存图片

            ImageIO.write(imageNew, imageFormat, new File(toPath));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

条形码和二维码todo

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

larance

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值