国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁(yè) Java Java入門 java實(shí)現(xiàn)添加圖片水印和文字水印

java實(shí)現(xiàn)添加圖片水印和文字水印

Mar 12, 2021 am 11:34 AM
java 圖片 特點(diǎn) 水印

java實(shí)現(xiàn)添加圖片水印和文字水印

我們經(jīng)常會(huì)在一些圖片或者圖片上看到某某公司或品牌的水印,那么我們可不可以自己在喜歡的圖片或文件上添加水印呢?答案當(dāng)然是沒(méi)問(wèn)題。

我們先來(lái)看看圖片水印:

----------------------------圖片水印----------------------------

1、添加文字水印

import?java.awt.Color;
import?java.awt.Font;
import?java.awt.Graphics2D;
import?java.awt.Image;
import?java.awt.image.BufferedImage;
import?java.io.File;
import?java.io.FileOutputStream;

import?javax.imageio.ImageIO;

/**
?*?給圖片添加文字水印
?*?
?*?@author?liqiang
?*
?*/
public?class?WaterMarkUtils?{

????/**
?????*?@param?args
?????*/
????public?static?void?main(String[]?args)?{
????????//?原圖位置,?輸出圖片位置,?水印文字顏色,?水印文字
????????new?WaterMarkUtils().mark("C:/Users/liqiang/Desktop/圖片/kdmt.jpg",?"C:/Users/liqiang/Desktop/圖片/kdmt1.jpg",
????????????????Color.red,?"圖片來(lái)源:XXX");
????}

????/**
?????*?圖片添加水印
?????*?
?????*?@param?srcImgPath
?????*????????????需要添加水印的圖片的路徑
?????*?@param?outImgPath
?????*????????????添加水印后圖片輸出路徑
?????*?@param?markContentColor
?????*????????????水印文字的顏色
?????*?@param?waterMarkContent
?????*????????????水印的文字
?????*/
????public?void?mark(String?srcImgPath,?String?outImgPath,?Color?markContentColor,?String?waterMarkContent)?{
????????try?{
????????????//?讀取原圖片信息
????????????File?srcImgFile?=?new?File(srcImgPath);
????????????Image?srcImg?=?ImageIO.read(srcImgFile);
????????????int?srcImgWidth?=?srcImg.getWidth(null);
????????????int?srcImgHeight?=?srcImg.getHeight(null);
????????????//?加水印
????????????BufferedImage?bufImg?=?new?BufferedImage(srcImgWidth,?srcImgHeight,?BufferedImage.TYPE_INT_RGB);
????????????Graphics2D?g?=?bufImg.createGraphics();
????????????g.drawImage(srcImg,?0,?0,?srcImgWidth,?srcImgHeight,?null);
????????????//?Font?font?=?new?Font("Courier?New",?Font.PLAIN,?12);
????????????Font?font?=?new?Font("宋體",?Font.PLAIN,?20);
????????????g.setColor(markContentColor);?//?根據(jù)圖片的背景設(shè)置水印顏色

????????????g.setFont(font);
????????????int?x?=?srcImgWidth?-?getWatermarkLength(waterMarkContent,?g)?-?3;
????????????int?y?=?srcImgHeight?-?3;
????????????//?int?x?=?(srcImgWidth?-?getWatermarkLength(watermarkStr,?g))?/?2;
????????????//?int?y?=?srcImgHeight?/?2;
????????????g.drawString(waterMarkContent,?x,?y);
????????????g.dispose();
????????????//?輸出圖片
????????????FileOutputStream?outImgStream?=?new?FileOutputStream(outImgPath);
????????????ImageIO.write(bufImg,?"jpg",?outImgStream);
????????????outImgStream.flush();
????????????outImgStream.close();
????????}?catch?(Exception?e)?{
????????????e.printStackTrace();
????????}
????}

????/**
?????*?獲取水印文字總長(zhǎng)度
?????*?
?????*?@param?waterMarkContent
?????*????????????水印的文字
?????*?@param?g
?????*?@return?水印文字總長(zhǎng)度
?????*/
????public?int?getWatermarkLength(String?waterMarkContent,?Graphics2D?g)?{
????????return?g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(),?0,?waterMarkContent.length());
????}
}

結(jié)果:

557496f1afabaaf0767c774a3a6c14a.png

2、給圖片添加圖片水印

import?java.awt.AlphaComposite;
import?java.awt.Graphics2D;
import?java.awt.Image;
import?java.awt.RenderingHints;
import?java.awt.image.BufferedImage;
import?java.io.File;
import?java.io.FileOutputStream;
import?java.io.OutputStream;

import?javax.imageio.ImageIO;
import?javax.swing.ImageIcon;

/**
?*?給圖片添加圖片
?*?
?*?@author?liqiang
?*
?*/
public?class?WaterMarkUtils?{

????/**
?????*?@param?args
?????*/
????public?static?void?main(String[]?args)?{
????????String?srcImgPath?=?"C:/Users/liqiang/Desktop/圖片/kdmt.jpg";
????????String?iconPath?=?"C:/Users/liqiang/Desktop/圖片/qlq.jpeg";
????????String?targerPath?=?"C:/Users/liqiang/Desktop/圖片/qlq1.jpeg";
????????String?targerPath2?=?"C:/Users/liqiang/Desktop/圖片/qlq2.jpeg";
????????//?給圖片添加水印
????????WaterMarkUtils.markImageByIcon(iconPath,?srcImgPath,?targerPath);
????????//?給圖片添加水印,水印旋轉(zhuǎn)-45
????????WaterMarkUtils.markImageByIcon(iconPath,?srcImgPath,?targerPath2,?-45);

????}

????/**
?????*?給圖片添加水印
?????*?
?????*?@param?iconPath
?????*????????????水印圖片路徑
?????*?@param?srcImgPath
?????*????????????源圖片路徑
?????*?@param?targerPath
?????*????????????目標(biāo)圖片路徑
?????*/
????public?static?void?markImageByIcon(String?iconPath,?String?srcImgPath,?String?targerPath)?{
????????markImageByIcon(iconPath,?srcImgPath,?targerPath,?null);
????}

????/**
?????*?給圖片添加水印、可設(shè)置水印圖片旋轉(zhuǎn)角度
?????*?
?????*?@param?iconPath
?????*????????????水印圖片路徑
?????*?@param?srcImgPath
?????*????????????源圖片路徑
?????*?@param?targerPath
?????*????????????目標(biāo)圖片路徑
?????*?@param?degree
?????*????????????水印圖片旋轉(zhuǎn)角度
?????*/
????public?static?void?markImageByIcon(String?iconPath,?String?srcImgPath,?String?targerPath,?Integer?degree)?{
????????OutputStream?os?=?null;
????????try?{
????????????Image?srcImg?=?ImageIO.read(new?File(srcImgPath));

????????????BufferedImage?buffImg?=?new?BufferedImage(srcImg.getWidth(null),?srcImg.getHeight(null),
????????????????????BufferedImage.TYPE_INT_RGB);

????????????//?得到畫筆對(duì)象
????????????//?Graphics?g=?buffImg.getGraphics();
????????????Graphics2D?g?=?buffImg.createGraphics();

????????????//?設(shè)置對(duì)線段的鋸齒狀邊緣處理
????????????g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,?RenderingHints.VALUE_INTERPOLATION_BILINEAR);

????????????g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null),?srcImg.getHeight(null),?Image.SCALE_SMOOTH),?0,
????????????????????0,?null);

????????????if?(null?!=?degree)?{
????????????????//?設(shè)置水印旋轉(zhuǎn)
????????????????g.rotate(Math.toRadians(degree),?(double)?buffImg.getWidth()?/?2,?(double)?buffImg.getHeight()?/?2);
????????????}

????????????//?水印圖象的路徑?水印一般為gif或者png的,這樣可設(shè)置透明度
????????????ImageIcon?imgIcon?=?new?ImageIcon(iconPath);

????????????//?得到Image對(duì)象。
????????????Image?img?=?imgIcon.getImage();

????????????float?alpha?=?0.5f;?//?透明度
????????????g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,?alpha));

????????????//?表示水印圖片的位置
????????????g.drawImage(img,?150,?300,?null);

????????????g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));

????????????g.dispose();

????????????os?=?new?FileOutputStream(targerPath);

????????????//?生成圖片
????????????ImageIO.write(buffImg,?"JPG",?os);

????????????System.out.println("圖片完成添加Icon印章。。。。。。");
????????}?catch?(Exception?e)?{
????????????e.printStackTrace();
????????}?finally?{
????????????try?{
????????????????if?(null?!=?os)
????????????????????os.close();
????????????}?catch?(Exception?e)?{
????????????????e.printStackTrace();
????????????}
????????}
????}
}

效果展示:

58b58b125977edf87ee184bbfa452a0.png

cfa050b5e3620a0da64f45eda2d6c70.png

(免費(fèi)視頻教程:java視頻教程

------------------------------PDF水印(itext添加水印)----------------------------

在這里就同時(shí)給PDF添加文字水印和圖片水印(每一頁(yè)都添加一個(gè)文字水印和圖片水印)

依賴的包:

<dependencies>
????????<dependency>
????????????<groupId>com.lowagie</groupId>
????????????<artifactId>itextasian</artifactId>
????????????<version>1.0</version>
????????</dependency>
????????<dependency>
????????????<groupId>com.lowagie</groupId>
????????????<artifactId>itext</artifactId>
????????????<version>2.1.7</version>
????????</dependency>
????</dependencies>

具體代碼:

import?java.awt.Color;
import?java.io.BufferedOutputStream;
import?java.io.File;
import?java.io.FileOutputStream;
import?java.io.IOException;
import?java.text.SimpleDateFormat;
import?java.util.Calendar;

import?com.lowagie.text.DocumentException;
import?com.lowagie.text.Element;
import?com.lowagie.text.Image;
import?com.lowagie.text.pdf.BaseFont;
import?com.lowagie.text.pdf.PdfContentByte;
import?com.lowagie.text.pdf.PdfGState;
import?com.lowagie.text.pdf.PdfReader;
import?com.lowagie.text.pdf.PdfStamper;

public?class?TestWaterPrint?{
????public?static?void?main(String[]?args)?throws?DocumentException,?IOException?{
????????//?要輸出的pdf文件
????????BufferedOutputStream?bos?=?new?BufferedOutputStream(new?FileOutputStream(new?File("E:/abc.pdf")));
????????Calendar?cal?=?Calendar.getInstance();
????????SimpleDateFormat?format?=?new?SimpleDateFormat("yyyy-MM-dd?hh:mm:ss");
????????//?將pdf文件先加水印然后輸出
????????setWatermark(bos,?"G:/1.pdf",?format.format(cal.getTime())?+?"??下載使用人:"?+?"測(cè)試user",?16);
????}

????/**
?????*?
?????*?@param?bos輸出文件的位置
?????*?@param?input
?????*????????????原PDF位置
?????*?@param?waterMarkName
?????*????????????頁(yè)腳添加水印
?????*?@param?permission
?????*????????????權(quán)限碼
?????*?@throws?DocumentException
?????*?@throws?IOException
?????*/
????public?static?void?setWatermark(BufferedOutputStream?bos,?String?input,?String?waterMarkName,?int?permission)
????????????throws?DocumentException,?IOException?{
????????PdfReader?reader?=?new?PdfReader(input);
????????PdfStamper?stamper?=?new?PdfStamper(reader,?bos);
????????int?total?=?reader.getNumberOfPages()?+?1;
????????PdfContentByte?content;
????????BaseFont?base?=?BaseFont.createFont("STSong-Light",?"UniGB-UCS2-H",?BaseFont.EMBEDDED);
????????PdfGState?gs?=?new?PdfGState();
????????for?(int?i?=?1;?i?<?total;?i++)?{
????????????content?=?stamper.getOverContent(i);//?在內(nèi)容上方加水印
????????????//?content?=?stamper.getUnderContent(i);//在內(nèi)容下方加水印
????????????gs.setFillOpacity(0.2f);
????????????//?content.setGState(gs);
????????????content.beginText();
????????????content.setColorFill(Color.LIGHT_GRAY);
????????????content.setFontAndSize(base,?50);
????????????content.setTextMatrix(70,?200);
????????????content.showTextAligned(Element.ALIGN_CENTER,?"公司內(nèi)部文件,請(qǐng)注意保密!",?300,?350,?55);
????????????Image?image?=?Image.getInstance("G:/2.jpeg");
????????????/*
??????????????img.setAlignment(Image.LEFT?|?Image.TEXTWRAP);
??????????????img.setBorder(Image.BOX);?img.setBorderWidth(10);
??????????????img.setBorderColor(BaseColor.WHITE);?img.scaleToFit(100072);//大小
??????????????img.setRotationDegrees(-30);//旋轉(zhuǎn)
?????????????*/
????????????image.setAbsolutePosition(200,?206);?//?set?the?first?background
????????????????????????????????????????????????????//?image?of?the?absolute
????????????image.scaleToFit(200,?200);
????????????content.addImage(image);
????????????content.setColorFill(Color.BLACK);
????????????content.setFontAndSize(base,?8);
????????????content.showTextAligned(Element.ALIGN_CENTER,?"下載時(shí)間:"?+?waterMarkName?+?"",?300,?10,?0);
????????????content.endText();

????????}
????????stamper.close();
????}
}

效果展示:

8eb731d148a52b4192d1569ac600046.png

補(bǔ)充:關(guān)于字體的用法

1、使用iTextAsian.jar中的字體?

BaseFont.createFont("STSong-Light",?"UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);

2、使用Windows系統(tǒng)字體

BaseFont.createFont("C:/WINDOWS/Fonts/SIMYOU.TTF",?BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);

3、使用資源字體(ClassPath) ,也就是將ttf字體拷貝到src目錄

BaseFont.createFont("/SIMYOU.TTF",?BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);

三種方法親測(cè)有效,而且使用itext自帶的字體就夠用了,可以正確的處理中文。

補(bǔ)充:關(guān)于獲取PDF頁(yè)面高度、寬度然后進(jìn)行動(dòng)態(tài)定位,比如說(shuō)根據(jù)頁(yè)面寬度實(shí)現(xiàn)平鋪水?。?/p>

package?cn.xm.exam.test;

import?java.awt.FontMetrics;
import?java.io.BufferedOutputStream;
import?java.io.File;
import?java.io.FileOutputStream;
import?java.io.IOException;

import?javax.swing.JLabel;

import?com.itextpdf.text.DocumentException;
import?com.itextpdf.text.Element;
import?com.itextpdf.text.Rectangle;
import?com.itextpdf.text.pdf.BaseFont;
import?com.itextpdf.text.pdf.PdfContentByte;
import?com.itextpdf.text.pdf.PdfGState;
import?com.itextpdf.text.pdf.PdfReader;
import?com.itextpdf.text.pdf.PdfStamper;

public?class?TestWaterPrint?{
????public?static?void?main(String[]?args)?throws?DocumentException,?IOException?{
????????//?要輸出的pdf文件
????????BufferedOutputStream?bos?=?new?BufferedOutputStream(new?FileOutputStream(new?File("F:/test1.pdf")));
????????//?將pdf文件先加水印然后輸出
????????setWatermark(bos,?"F:/test.pdf",?"測(cè)試user");
????}

????/**
?????*?
?????*?@param?bos輸出文件的位置
?????*?@param?input
?????*????????????原PDF位置
?????*?@param?waterMarkName
?????*????????????頁(yè)腳添加水印
?????*?@throws?DocumentException
?????*?@throws?IOException
?????*/
????public?static?void?setWatermark(BufferedOutputStream?bos,?String?input,?String?waterMarkName)
????????????throws?DocumentException,?IOException?{

????????PdfReader?reader?=?new?PdfReader(input);
????????PdfStamper?stamper?=?new?PdfStamper(reader,?bos);

????????//?獲取總頁(yè)數(shù)?+1,?下面從1開始遍歷
????????int?total?=?reader.getNumberOfPages()?+?1;
????????//?使用classpath下面的字體庫(kù)
????????BaseFont?base?=?null;
????????try?{
????????????base?=?BaseFont.createFont("/calibri.ttf",?BaseFont.IDENTITY_H,?BaseFont.NOT_EMBEDDED);
????????}?catch?(Exception?e)?{
????????????//?日志處理
????????????e.printStackTrace();
????????}

????????//?間隔
????????int?interval?=?-5;
????????//?獲取水印文字的高度和寬度
????????int?textH?=?0,?textW?=?0;
????????JLabel?label?=?new?JLabel();
????????label.setText(waterMarkName);
????????FontMetrics?metrics?=?label.getFontMetrics(label.getFont());
????????textH?=?metrics.getHeight();
????????textW?=?metrics.stringWidth(label.getText());
????????System.out.println("textH:?"?+?textH);
????????System.out.println("textW:?"?+?textW);

????????//?設(shè)置水印透明度
????????PdfGState?gs?=?new?PdfGState();
????????gs.setFillOpacity(0.4f);
????????gs.setStrokeOpacity(0.4f);

????????Rectangle?pageSizeWithRotation?=?null;
????????PdfContentByte?content?=?null;
????????for?(int?i?=?1;?i?<?total;?i++)?{
????????????//?在內(nèi)容上方加水印
????????????content?=?stamper.getOverContent(i);
????????????//?在內(nèi)容下方加水印
????????????//?content?=?stamper.getUnderContent(i);
????????????content.saveState();
????????????content.setGState(gs);

????????????//?設(shè)置字體和字體大小
????????????content.beginText();
????????????content.setFontAndSize(base,?20);

????????????//?獲取每一頁(yè)的高度、寬度
????????????pageSizeWithRotation?=?reader.getPageSizeWithRotation(i);
????????????float?pageHeight?=?pageSizeWithRotation.getHeight();
????????????float?pageWidth?=?pageSizeWithRotation.getWidth();

????????????//?根據(jù)紙張大小多次添加,?水印文字成30度角傾斜
????????????for?(int?height?=?interval?+?textH;?height?<?pageHeight;?height?=?height?+?textH?*?3)?{
????????????????for?(int?width?=?interval?+?textW;?width?<?pageWidth?+?textW;?width?=?width?+?textW?*?2)?{
????????????????????content.showTextAligned(Element.ALIGN_LEFT,?waterMarkName,?width?-?textW,?height?-?textH,?30);
????????????????}
????????????}

????????????content.endText();
????????}

????????//?關(guān)流
????????stamper.close();
????????reader.close();
????}
}

結(jié)果展示:

3d8f80a59e6deec978d384e7d12f6eb.png

補(bǔ)充:關(guān)于itext添加傾斜字體的水印

上面使用的是BaseFont,無(wú)法添加樣式,F(xiàn)ont可以添加樣式,但是setFontAndSize方法不接受Font參數(shù)。所以只能變通實(shí)現(xiàn):

例如:在每頁(yè)右下角生成傾斜水印

package?cn.xm.exam.test;

import?java.io.BufferedOutputStream;
import?java.io.File;
import?java.io.FileOutputStream;
import?java.io.IOException;

import?com.itextpdf.text.DocumentException;
import?com.itextpdf.text.Rectangle;
import?com.itextpdf.text.pdf.BaseFont;
import?com.itextpdf.text.pdf.PdfContentByte;
import?com.itextpdf.text.pdf.PdfGState;
import?com.itextpdf.text.pdf.PdfReader;
import?com.itextpdf.text.pdf.PdfStamper;

public?class?TestWaterPrint?{
????public?static?void?main(String[]?args)?throws?DocumentException,?IOException?{
????????//?要輸出的pdf文件
????????BufferedOutputStream?bos?=?new?BufferedOutputStream(new?FileOutputStream(new?File("F:/test2.pdf")));
????????//?將pdf文件先加水印然后輸出
????????setWatermark(bos,?"F:/test.pdf",?"測(cè)試user123456789");
????}

????/**
?????*?
?????*?@param?bos輸出文件的位置
?????*?@param?input
?????*????????????原PDF位置
?????*?@param?waterMarkName
?????*????????????頁(yè)腳添加水印
?????*?@throws?DocumentException
?????*?@throws?IOException
?????*/
????public?static?void?setWatermark(BufferedOutputStream?bos,?String?input,?String?waterMarkName)
????????????throws?DocumentException,?IOException?{

????????PdfReader?reader?=?new?PdfReader(input);
????????PdfStamper?stamper?=?new?PdfStamper(reader,?bos);

????????//?獲取總頁(yè)數(shù)?+1,?下面從1開始遍歷
????????int?total?=?reader.getNumberOfPages()?+?1;
????????//?使用classpath下面的字體庫(kù)
????????BaseFont?base?=?null;
????????try?{
????????????base?=?BaseFont.createFont("/calibri.ttf",?BaseFont.IDENTITY_H,?BaseFont.NOT_EMBEDDED);
????????}?catch?(Exception?e)?{
????????????//?日志處理
????????????e.printStackTrace();
????????}

????????//?設(shè)置水印透明度
????????PdfGState?gs?=?new?PdfGState();
????????gs.setFillOpacity(0.4f);
????????gs.setStrokeOpacity(0.4f);

????????PdfContentByte?content?=?null;
????????for?(int?i?=?1;?i?<?total;?i++)?{
????????????//?在內(nèi)容上方加水印
????????????content?=?stamper.getOverContent(i);
????????????//?在內(nèi)容下方加水印
????????????//?content?=?stamper.getUnderContent(i);
????????????content.saveState();
????????????content.setGState(gs);

????????????//?設(shè)置字體和字體大小
????????????content.beginText();
????????????content.setFontAndSize(base,?10);

????????????//?設(shè)置字體樣式
????????????float?ta?=?1F,?tb?=?0F,?tc?=?0F,?td?=?1F,?tx?=?0F,?ty?=?0F;
????????????//?設(shè)置加粗(加粗)
????????????ta?+=?0.25F;
????????????td?+=?0.05F;
????????????ty?-=?0.2F;
????????????//?設(shè)置傾斜(傾斜程序自己改)
????????????tc?+=?0.8F;
????????????content.setTextMatrix(ta,?tb,?tc,?td,?tx,?ty);

????????????//?設(shè)置相對(duì)于左下角位置(向右為x,向上為y)
????????????content.moveText(300F,?5F);
????????????//?顯示text
????????????content.showText(waterMarkName);

????????????content.endText();
????????????content.stroke();
????????????content.restoreState();
????????}

????????//?關(guān)流
????????stamper.close();
????????reader.close();
????}
}

結(jié)果展示:

02ffebdbf58d7f7709cf73cedac5853.png

相關(guān)推薦:java入門教程

以上是java實(shí)現(xiàn)添加圖片水印和文字水印的詳細(xì)內(nèi)容。更多信息請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請(qǐng)聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動(dòng)的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機(jī)

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁(yè)開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)代碼編輯軟件(SublimeText3)

如何在Java的地圖上迭代? 如何在Java的地圖上迭代? Jul 13, 2025 am 02:54 AM

遍歷Java中的Map有三種常用方法:1.使用entrySet同時(shí)獲取鍵和值,適用于大多數(shù)場(chǎng)景;2.使用keySet或values分別遍歷鍵或值;3.使用Java8的forEach簡(jiǎn)化代碼結(jié)構(gòu)。entrySet返回包含所有鍵值對(duì)的Set集合,每次循環(huán)獲取Map.Entry對(duì)象,適合頻繁訪問(wèn)鍵和值的情況;若只需鍵或值,可分別調(diào)用keySet()或values(),也可在遍歷鍵時(shí)通過(guò)map.get(key)獲取值;Java8中可通過(guò)Lambda表達(dá)式使用forEach((key,value)-&gt

Java可選示例 Java可選示例 Jul 12, 2025 am 02:55 AM

Optional能清晰表達(dá)意圖并減少null判斷的代碼噪音。1.Optional.ofNullable是處理可能為null對(duì)象的常用方式,如從map中取值時(shí)可結(jié)合orElse提供默認(rèn)值,邏輯更清晰簡(jiǎn)潔;2.通過(guò)鏈?zhǔn)秸{(diào)用map實(shí)現(xiàn)嵌套取值,安全地避免NPE,任一環(huán)節(jié)為null則自動(dòng)終止并返回默認(rèn)值;3.filter可用于條件篩選,滿足條件才繼續(xù)執(zhí)行后續(xù)操作,否則直接跳到orElse,適合輕量級(jí)業(yè)務(wù)判斷;4.不建議過(guò)度使用Optional,如基本類型或簡(jiǎn)單邏輯中其反而增加復(fù)雜度,部分場(chǎng)景直接返回nu

如何修復(fù)java.io.notserializable Exception? 如何修復(fù)java.io.notserializable Exception? Jul 12, 2025 am 03:07 AM

遇到j(luò)ava.io.NotSerializableException的核心解決方法是確保所有需序列化的類實(shí)現(xiàn)Serializable接口,并檢查嵌套對(duì)象的序列化支持。1.給主類添加implementsSerializable;2.確保類中自定義字段對(duì)應(yīng)的類也實(shí)現(xiàn)Serializable;3.用transient標(biāo)記不需要序列化的字段;4.檢查集合或嵌套對(duì)象中的非序列化類型;5.查看異常信息定位具體哪個(gè)類未實(shí)現(xiàn)接口;6.對(duì)無(wú)法修改的類考慮替換設(shè)計(jì),如保存關(guān)鍵數(shù)據(jù)或使用可序列化的中間結(jié)構(gòu);7.考慮改

Java中的可比較與比較器 Java中的可比較與比較器 Jul 13, 2025 am 02:31 AM

在Java中,Comparable用于類內(nèi)部定義默認(rèn)排序規(guī)則,Comparator用于外部靈活定義多種排序邏輯。1.Comparable是類自身實(shí)現(xiàn)的接口,通過(guò)重寫compareTo()方法定義自然順序,適用于類有固定、最常用的排序方式,如String或Integer。2.Comparator是外部定義的函數(shù)式接口,通過(guò)compare()方法實(shí)現(xiàn),適合同一類需要多種排序方式、無(wú)法修改類源碼或排序邏輯經(jīng)常變化的情況。兩者區(qū)別在于Comparable只能定義一種排序邏輯且需修改類本身,而Compar

如何處理Java中的字符編碼問(wèn)題? 如何處理Java中的字符編碼問(wèn)題? Jul 13, 2025 am 02:46 AM

處理Java中的字符編碼問(wèn)題,關(guān)鍵是在每一步都明確指定使用的編碼。1.讀寫文本時(shí)始終指定編碼,使用InputStreamReader和OutputStreamWriter并傳入明確的字符集,避免依賴系統(tǒng)默認(rèn)編碼。2.在網(wǎng)絡(luò)邊界處理字符串時(shí)確保兩端一致,設(shè)置正確的Content-Type頭并用庫(kù)顯式指定編碼。3.謹(jǐn)慎使用String.getBytes()和newString(byte[]),應(yīng)始終手動(dòng)指定StandardCharsets.UTF_8以避免平臺(tái)差異導(dǎo)致的數(shù)據(jù)損壞??傊?,通過(guò)在每個(gè)階段

如何在Java解析JSON? 如何在Java解析JSON? Jul 11, 2025 am 02:18 AM

解析JSON在Java中的常見方式有三種:使用Jackson、Gson或org.json。1.Jackson適合大多數(shù)項(xiàng)目,性能好且功能全面,支持對(duì)象與JSON字符串之間的轉(zhuǎn)換及注解映射;2.Gson更適合Android項(xiàng)目或輕量級(jí)需求,使用簡(jiǎn)單但處理復(fù)雜結(jié)構(gòu)和高性能場(chǎng)景略遜;3.org.json適用于簡(jiǎn)單任務(wù)或小腳本,不推薦用于大型項(xiàng)目,因其靈活性和類型安全不足。選擇應(yīng)根據(jù)實(shí)際需求決定。

Java方法參考解釋了 Java方法參考解釋了 Jul 12, 2025 am 02:59 AM

方法引用是Java中一種簡(jiǎn)化Lambda表達(dá)式的寫法,使代碼更簡(jiǎn)潔。它不是新語(yǔ)法,而是Java8引入的Lambda表達(dá)式的一種快捷方式,適用于函數(shù)式接口的上下文。其核心在于將已有方法直接作為函數(shù)式接口的實(shí)現(xiàn)來(lái)使用。例如System.out::println等價(jià)于s->System.out.println(s)。方法引用主要有四種形式:1.靜態(tài)方法引用(ClassName::staticMethodName);2.實(shí)例方法引用(綁定到特定對(duì)象,instance::methodName);3.

新電子郵件的Outlook快捷方式 新電子郵件的Outlook快捷方式 Jul 11, 2025 am 03:25 AM

在Outlook中快速新建郵件的方法如下:1.桌面版使用快捷鍵Ctrl Shift M,可直接彈出新郵件窗口;2.網(wǎng)頁(yè)版可通過(guò)創(chuàng)建包含JavaScript的書簽(如javascript:document.querySelector("divrole='button'").click())實(shí)現(xiàn)一鍵新建郵件;3.使用瀏覽器插件(如Vimium、CrxMouseGestures)自定義快捷鍵觸發(fā)“新建郵件”按鈕;4.Windows用戶還可通過(guò)右鍵任務(wù)欄Outlook圖標(biāo)選擇“新建電

See all articles