「java附件处理」Java图片处理

博主:adminadmin 2022-11-26 02:02:07 94

本篇文章给大家谈谈java附件处理,以及Java图片处理对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

java中如何实现向已有的PDF文件插入附件?

可以用Spire.Pdf for Java类库给PDF文档添加附件,下面的代码是插入Excel和Word附件给你参考:

import com.spire.pdf.annotations.*;

import com.spire.pdf.attachments.PdfAttachment;

import com.spire.pdf.graphics.*;

import java.awt.*;

import java.awt.geom.Dimension2D;

import java.awt.geom.Rectangle2D;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

public class AttachFiles {

public static void main(String[] args) throws IOException {

//创建PdfDocument对象

PdfDocument doc = new PdfDocument();

//加载PDF文档

doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");

//添加附件到PDF

PdfAttachment attachment = new PdfAttachment("C:\\Users\\Administrator\\Desktop\\使用说明书.docx");

doc.getAttachments().add(attachment);

//绘制标签

String label = "财务报表.xlsx";

PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial Unicode MS",Font.PLAIN,12),true);

double x = 35;

double y = doc.getPages().get(0).getActualSize().getHeight() - 200;

doc.getPages().get(0).getCanvas().drawString(label, font, PdfBrushes.getOrange(), x, y);

//添加注释附件到PDF

String filePath = "C:\\Users\\Administrator\\Desktop\\财务报表.xlsx";

byte[] data = toByteArray(filePath);

Dimension2D size = font.measureString(label);

Rectangle2D bound = new Rectangle2D.Float((float) (x + size.getWidth() + 2), (float) y, 10, 15);

PdfAttachmentAnnotation annotation = new PdfAttachmentAnnotation(bound, filePath, data);

annotation.setColor(new PdfRGBColor(new Color(0, 128, 128)));

annotation.setFlags(PdfAnnotationFlags.Default);

annotation.setIcon(PdfAttachmentIcon.Graph);

annotation.setText("点击打开财务报表.xlsx");

doc.getPages().get(0).getAnnotationsWidget().add(annotation);

//保存文档

doc.saveToFile("Attachments.pdf");

}

//读取文件到byte数组

public static byte[] toByteArray(String filePath) throws IOException {

File file = new File(filePath);

long fileSize = file.length();

if (fileSize Integer.MAX_VALUE) {

System.out.println("file too big...");

return null;

}

FileInputStream fi = new FileInputStream(file);

byte[] buffer = new byte[(int) fileSize];

int offset = 0;

int numRead = 0;

while (offset buffer.length (numRead = fi.read(buffer, offset, buffer.length - offset)) = 0) {

offset += numRead;

}

if (offset != buffer.length) {

throw new IOException("Could not completely read file "

+ file.getName());

}

fi.close();

return buffer;

}

}

效果:

java怎么实现上传附件的功能

上传附件,实际上就是将文件存储到远程服务器,进行临时存储。举例:

**

* 上传文件

*

* @param fileName

* @param plainFilePath 文件路径路径

* @param filepath

* @return

* @throws Exception

*/

public static String fileUploadByFtp(String plainFilePath, String fileName, String filepath) throws Exception {

FileInputStream fis = null;

ByteArrayOutputStream bos = null;

FTPClient ftpClient = new FTPClient();

String bl = "false";

try {

fis = new FileInputStream(plainFilePath);

bos = new ByteArrayOutputStream(fis.available());

byte[] buffer = new byte[1024];

int count = 0;

while ((count = fis.read(buffer)) != -1) {

bos.write(buffer, 0, count);

}

bos.flush();

Log.info("加密上传文件开始");

Log.info("连接远程上传服务器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);

ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);

ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);

FTPFile[] fs;

fs = ftpClient.listFiles();

for (FTPFile ff : fs) {

if (ff.getName().equals(filepath)) {

bl="true";

ftpClient.changeWorkingDirectory("/"+filepath+"");

}

}

Log.info("检查文件路径是否存在:/"+filepath);

if("false".equals(bl)){

ViewUtil.dataSEErrorPerformedCommon( "查询文件路径不存在:"+"/"+filepath);

return bl;

}

ftpClient.setBufferSize(1024);

ftpClient.setControlEncoding("GBK");

// 设置文件类型(二进制)

ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

ftpClient.storeFile(fileName, fis);

Log.info("上传文件成功:"+fileName+"。文件保存路径:"+"/"+filepath+"/");

return bl;

} catch (Exception e) {

throw e;

} finally {

if (fis != null) {

try {

fis.close();

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e);

}

}

if (bos != null) {

try {

bos.close();

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e);

}

}

}

}

备注:只需要修改上传的服务器地址、用户名、密码即可进行服务器访问上传。根据实际需要修改即可。

JAVA 怎么删除上传到硬盘的附件

import java.io.File;

/**

*

* 2007-11-27

* 删除文件或目录

* @author 计春旭 E-mail: jichunxu@yahoo.com.cn

* @version 创建时间:Jun 16, 2009 9:50:44 AM

* @see java.lang.Class

* @since JDK1.5

*/

public class DeleteFileUtil {

/**

* 删除文件,可以是单个文件或文件夹

* @param fileName 待删除的文件名

* @return 文件删除成功返回true,否则返回false

*/

public static boolean delete(String fileName){

File file = new File(fileName);

if(!file.exists()){

System.out.println("删除文件失败:"+fileName+"文件不存在");

return false;

}else{

if(file.isFile()){

return deleteFile(fileName);

}else{

return deleteDirectory(fileName);

}

}

}

/**

* 删除单个文件

* @param fileName 被删除文件的文件名

* @return 单个文件删除成功返回true,否则返回false

*/

public static boolean deleteFile(String fileName){

File file = new File(fileName);

if(file.isFile() file.exists()){

file.delete();

System.out.println("删除单个文件"+fileName+"成功!");

return true;

}else{

System.out.println("删除单个文件"+fileName+"失败!");

return false;

}

}

/**

* 删除目录(文件夹)以及目录下的文件

* @param dir 被删除目录的文件路径

* @return 目录删除成功返回true,否则返回false

*/

public static boolean deleteDirectory(String dir){

//如果dir不以文件分隔符结尾,自动添加文件分隔符

if(!dir.endsWith(File.separator)){

dir = dir+File.separator;

}

File dirFile = new File(dir);

//如果dir对应的文件不存在,或者不是一个目录,则退出

if(!dirFile.exists() || !dirFile.isDirectory()){

System.out.println("删除目录失败"+dir+"目录不存在!");

return false;

}

boolean flag = true;

//删除文件夹下的所有文件(包括子目录)

File[] files = dirFile.listFiles();

for(int i=0;ifiles.length;i++){

//删除子文件

if(files[i].isFile()){

flag = deleteFile(files[i].getAbsolutePath());

if(!flag){

break;

}

}

//删除子目录

else{

flag = deleteDirectory(files[i].getAbsolutePath());

if(!flag){

break;

}

}

}

if(!flag){

System.out.println("删除目录失败");

return false;

}

//删除当前目录

if(dirFile.delete()){

System.out.println("删除目录"+dir+"成功!");

return true;

}else{

System.out.println("删除目录"+dir+"失败!");

return false;

}

}

//删除文件夹

//param folderPath 文件夹完整绝对路径

public static void delFolder(String folderPath) {

try {

delAllFile(folderPath); //删除完里面所有内容

String filePath = folderPath;

filePath = filePath.toString();

java.io.File myFilePath = new java.io.File(filePath);

myFilePath.delete(); //删除空文件夹

} catch (Exception e) {

e.printStackTrace();

}

}

//删除指定文件夹下所有文件

//param path 文件夹完整绝对路径

public static boolean delAllFile(String path) {

boolean flag = false;

File file = new File(path);

if (!file.exists()) {

return flag;

}

if (!file.isDirectory()) {

return flag;

}

String[] tempList = file.list();

File temp = null;

for (int i = 0; i tempList.length; i++) {

if (path.endsWith(File.separator)) {

temp = new File(path + tempList[i]);

} else {

temp = new File(path + File.separator + tempList[i]);

}

if (temp.isFile()) {

temp.delete();

}

if (temp.isDirectory()) {

delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件

delFolder(path + "/" + tempList[i]);//再删除空文件夹

flag = true;

}

}

return flag;

}

public static void main(String[] args) {

//String fileName = "g:/temp/xwz.txt";

//DeleteFileUtil.deleteFile(fileName);

String fileDir = "D:\\apache-tomcat-6.0.18\\webapps\\cyfy\\upload\\disk\\1245117448156\\JavaScript486.rar";

//DeleteFileUtil.deleteDirectory(fileDir);

DeleteFileUtil.delete(fileDir);

DeleteFileUtil t = new DeleteFileUtil();

delFolder("c:/bb");

System.out.println("deleted");

}

}

java 代码发邮件怎么添加附件

实现java发送邮件的过程大体有以下几步:

准备一个properties文件,该文件中存放SMTP服务器地址等参数。

利用properties创建一个Session对象

利用Session创建Message对象,然后设置邮件主题和正文

利用Transport对象发送邮件

需要的jar有2个:activation.jar和mail.jar发送附件,需要用到Multipart对象。

import java.io.File;

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.mail.BodyPart;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Multipart;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

import javax.mail.internet.MimeUtility;

public class JavaMailWithAttachment {

    private MimeMessage message;

    private Session session;

    private Transport transport;

    private String mailHost = "";

    private String sender_username = "";

    private String sender_password = "";

    private Properties properties = new Properties();

    /*

     * 初始化方法

     */

    public JavaMailWithAttachment(boolean debug) {

        InputStream in = JavaMailWithAttachment.class.getResourceAsStream("MailServer.properties");

        try {

            properties.load(in);

            this.mailHost = properties.getProperty("mail.smtp.host");

            this.sender_username = properties.getProperty("mail.sender.username");

            this.sender_password = properties.getProperty("mail.sender.password");

        } catch (IOException e) {

            e.printStackTrace();

        }

        session = Session.getInstance(properties);

        session.setDebug(debug);// 开启后有调试信息

        message = new MimeMessage(session);

    }

    /**

     * 发送邮件

     * 

     * @param subject

     *            邮件主题

     * @param sendHtml

     *            邮件内容

     * @param receiveUser

     *            收件人地址

     * @param attachment

     *            附件

     */

    public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) {

        try {

            // 发件人

            InternetAddress from = new InternetAddress(sender_username);

            message.setFrom(from);

            // 收件人

            InternetAddress to = new InternetAddress(receiveUser);

            message.setRecipient(Message.RecipientType.TO, to);

            // 邮件主题

            message.setSubject(subject);

            // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件

            Multipart multipart = new MimeMultipart();

            

            // 添加邮件正文

            BodyPart contentPart = new MimeBodyPart();

            contentPart.setContent(sendHtml, "text/html;charset=UTF-8");

            multipart.addBodyPart(contentPart);

            

            // 添加附件的内容

            if (attachment != null) {

                BodyPart attachmentBodyPart = new MimeBodyPart();

                DataSource source = new FileDataSource(attachment);

                attachmentBodyPart.setDataHandler(new DataHandler(source));

                

                // 网上流传的解决文件名乱码的方法,其实用MimeUtility.encodeWord就可以很方便的搞定

                // 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码

                //sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();

                //messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?=");

                

                //MimeUtility.encodeWord可以避免文件名乱码

                attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));

                multipart.addBodyPart(attachmentBodyPart);

            }

            

            // 将multipart对象放到message中

            message.setContent(multipart);

            // 保存邮件

            message.saveChanges();

            transport = session.getTransport("smtp");

            // smtp验证,就是你用来发邮件的邮箱用户名密码

            transport.connect(mailHost, sender_username, sender_password);

            // 发送

            transport.sendMessage(message, message.getAllRecipients());

            System.out.println("send success!");

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            if (transport != null) {

                try {

                    transport.close();

                } catch (MessagingException e) {

                    e.printStackTrace();

                }

            }

        }

    }

    public static void main(String[] args) {

        JavaMailWithAttachment se = new JavaMailWithAttachment(true);

        File affix = new File("c:\\测试-test.txt");

        se.doSendHtmlEmail("邮件主题", "邮件内容", "xxx@XXX.com", affix);//

    }

}

java附件处理的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于Java图片处理、java附件处理的信息别忘了在本站进行查找喔。

The End

发布于:2022-11-26,除非注明,否则均为首码项目网原创文章,转载请注明出处。