java项目打包后如何读写项目中的文件

当Java项目打包成jar后,无法直接对jar内的文件进行写操作。本文介绍了将配置文件放在与jar包同级的projectFile文件夹中,从而实现读写操作的方法。通过调整文件路径,利用`System.getProperty("user.dir")`获取当前目录,确保在打包前后都能正确找到文件。同时,展示了如何在Freemarker模板引擎中读写文件的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


        写了一个项目,其中放了一些配置文件,因为项目需求,要读写这些文件。在eclipse中可以正常读写操作,但是打包之后发现不能执行写操作,但是可以读取。上百度查询,都是如何读取项目中的文件,但是没有涉及到写操作,后来查到百度上有人说:
如果非要往jar里面写文本,还要重新导入被编写的jar才可以读到你修改之后的内容,很麻烦。
链接:http://zhidao.baidu.com/link?url=kgNpRcBzkHhd4O5NuvQfC_sEOx8b_EzDCDvaXc_eZLdA144A55qIadf0KCEwNf2mPPNwI6KK_I7MIjvDgIp_xa

既然这样,只能转变方向,将这些文件都放入一个文件夹projectFile中,该文件夹与jar包同在一个目录下,为打包之前这个文件夹和工程文件同目录。
项目结构截图:

打包之前projectFile文件夹与工程文件的位置截图:

打包之后的jar包与projectFile文件夹的位置截图:

源码:

package com.freemaker;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.swing.JOptionPane;

import sun.misc.*;
import freemarker.cache.URLTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreemakerDemo1 {

private static Configuration cfg; //模版配置对象
private static File file=null;

public static void init() throws Exception {
//初始化FreeMarker配置
//创建一个Configuration实例
cfg = new Configuration();
String userDir=System.getProperty("user.dir");
String p="";
file=new File(userDir+"/projectFile");
if(!file.exists()){
file=new File(userDir);
p=file.getParent();
file=new File(p+"/projectFile");//

}
//设置FreeMarker的模版文件夹位置
// cfg.setDirectoryForTemplateLoading(new File("G:\\testprojects\\freemarkertest\\src"));
// cfg.setDirectoryForTemplateLoading(file);//可以
cfg.setTemplateLoader(new URLTemplateLoader() {// 获得模板的url
@Override
protected URL getURL(String filePath) {
return FreemakerDemo1.class
.getResource("/resource/部门申请审批表20151226.xml");
}
});
cfg.setEncoding(Locale.getDefault(), "utf-8");
JOptionPane.showMessageDialog(null, "模板位置设置成功!");
}

public static void main(String[] args) throws Exception {
// String userDir=System.getProperty("user.dir");
// String p="";
// file=new File(userDir+"/projectFile");//a.txt,
// if(!file.exists()){
// file=new File(userDir);
// p=file.getParent();
// file=new File(p+"/projectFile");///保密要害部门部位报废申请审批表20151226.xml
//
// }
init();
createStringModel();
JOptionPane.showMessageDialog(null, "String模板成功演示");
processFile();
}
//1、通过String来创建模版对象,并执行插值处理
public static void createStringModel() throws IOException, TemplateException {
//创建一个模版对象
Template t = new Template(null, new StringReader("用户名:${user};URL: ${url};姓名:  ${name}"), null);
//创建插值的Map
Map map = new HashMap();
map.put("user", "lavasoft");
map.put("url", "http://www.baidu.com/");
map.put("name", "百度");
//执行插值,并输出到指定的输出流中
t.process(map, new OutputStreamWriter(System.out));
}

//2、通过文件来创建模版对象,并执行插值操作
public static void processFile() throws Exception {
//构造填充数据的Map
Map map = new HashMap();
JOptionPane.showMessageDialog(null, "freemaker执行开始");
File f=new File(file.getPath()+"/2016012500001"+".doc");
OutputStreamWriter out=new OutputStreamWriter(new FileOutputStream(f),"utf-8");
map.put("image", getImageStr());
map.put("formno", "20160125001");
map.put("deptname", "事业部");
map.put("date", "2016-01-25");
map.put("name", "张三丰");

map.put("idCard", "0574201601251203");
map.put("type", "管理");
map.put("deptStaff", "经理");
map.put("usernum", "201601252596");
map.put("securitymeasure", "做好安全措施");
map.put("reason", "工作调整");
//创建模版对象
Template t = cfg.getTemplate("resource/部门申请审批表20151226.xml");
//在模版上执行插值操作,并输出到制定的输出流中
t.process(map, out);
JOptionPane.showMessageDialog(null, "freemaker执行成功");
out.flush();
out.close();

}
public static String getImageStr() {
String imgFile = file.getPath()+"/barcode.png";
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(in!=null){
in.close();
}
} catch (Exception e2) {
}
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}

}

 其中使用到了freemarker.jar包。
打包之后执行jar程序,projectFile文件可以正常生成word文件,图片也可以正常写入。
projectFile文件截图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值