createtempfile不生成随机名字(奇怪:我用java创建的临时文件,指定的文件名后面会出现一串数字)

本文目录
- 奇怪:我用java创建的临时文件,指定的文件名后面会出现一串数字
- Java在指定目录中创建文件,为什么输出不是C:\JavaTemp.javatemp 文件名后面的数字是什么意思求指点
- android 为什么我创建的临时文件名里有一串随机数
- df.to csv 把文件写入到哪里
- JSP页面将查询结果导出为CSV文件
- java 如何给pdf文件加水印
奇怪:我用java创建的临时文件,指定的文件名后面会出现一串数字
本来就是这样的啊。
File createTempFile(String prefix, String suffix, File directory)
其中prefix是前缀,suffix是后缀。生成的文件名是由一串随机数字加上前缀后缀形成的
Java在指定目录中创建文件,为什么输出不是C:\JavaTemp.javatemp 文件名后面的数字是什么意思求指点
你这是创建临时文件,系统会自动加上一个随机数防止重复
这种问题最直接最好的办法直接看源码:
public static File createTempFile(String prefix, String suffix,
File directory)
throws IOException
{
if (prefix == null) throw new NullPointerException();
if (prefix.length() 《 3)
throw new IllegalArgumentException("Prefix string too short");
String s = (suffix == null) ? ".tmp" : suffix;
if (directory == null) {
String tmpDir = LazyInitialization.temporaryDirectory();
directory = new File(tmpDir, fs.prefixLength(tmpDir));
}
SecurityManager sm = System.getSecurityManager();
File f;
do {
f = generateFile(prefix, s, directory);
} while (!checkAndCreate(f.getPath(), sm));
return f;
}
private static File generateFile(String prefix, String suffix, File dir)
throws IOException
{
long n = LazyInitialization.random.nextLong();
if (n == Long.MIN_VALUE) {
n = 0; // corner case
} else {
n = Math.abs(n);
}
return new File(dir, prefix + Long.toString(n) + suffix);
}
然后那串数字生成的源头:
return ((long)(next(32)) 《《 32) + next(32);
android 为什么我创建的临时文件名里有一串随机数
File.createTempFile()
这个方法内部实现的时候 就是添加了随机数。防止文件重复,创建失败。
df.to csv 把文件写入到哪里
你好运气啊~~我前几天刚做过这个~~~下面这大段代码是2个方法除了在第一个方法里将文件名和要写入的表头改成你自己的之外其余照搬就可以了最后只需用在你的主方法里调用这两个方法就行了不易理解的地方我做了注释祝你成功~~~publicFileputOutTaskToExcelFile(ListgetPutOutTaskResult){//在我的代码里,getPutOutTaskResult是我需要导出的信息列表,你换成你的就行BufferedWriterout=null;intrandom=(int)(Math.random()*1000+1);//这个随机数只是为了让后面生成的文件名不重复而已FileexcelFile=null;try{excelFile=File.createTempFile("你的文件名"+random,".csv");//生成一个csv临时文件excelFile.deleteOnExit();}catch(IOExceptione1){e1.printStackTrace();}inti=1;try{out=newBufferedWriter(newFileWriter(excelFile));out.write("序号"+","+"用户号码"+","+"是否成功"+","+"失败原因"+",");//换成你需要的表头out.newLine();IteratorresultIterator=getPutOutTaskResult.iterator();while(resultIterator.hasNext()){Ee=resultIterator.next();out.write(i+","+A+","+B+","+C);//A、B、C等等都换上你自己的就可以i是一个自增序号out.newLine();i++;}out.flush();}catch(IOExceptione){e.printStackTrace();}finally{if(out!=null){try{out.close();}catch(IOExceptione){e.printStackTrace();}}}returnexcelFile;}/***将服务器端生成的Excel文件提供给客户端下载**@paramrequest*@paramresponse*@paramtempFile*/privatevoiddownload(HttpServletRequestrequest,HttpServletResponseresponse,FiletempFile){Stringfilenamedownload=tempFile.toString();Stringfilenamedisplay=tempFile.getName();try{filenamedisplay=URLEncoder.encode(filenamedisplay,"UTF-8");}catch(UnsupportedEncodingExceptione1){e1.printStackTrace();}response.addHeader("Content-Disposition","attachment;filename="+filenamedisplay);OutputStreamoutput=null;FileInputStreamfis=null;try{output=response.getOutputStream();fis=newFileInputStream(filenamedownload);byte;inti=0;while((i=fis.read(b))》0){output.write(b,0,i);}output.flush();}catch(Exceptione){e.printStackTrace();}finally{if(fis!=null){try{fis.close();}catch(IOExceptione){e.printStackTrace();}fis=null;}if(output!=null){try{output.close();}catch(IOExceptione){e.printStackTrace();}output=null;}}}
JSP页面将查询结果导出为CSV文件
你好运气啊~~我前几天刚做过这个~~~
下面这大段代码是2个方法 除了在第一个方法里将文件名和要写入的表头改成你自己的之外其余照搬就可以了 最后只需用在你的主方法里调用这两个方法就行了
不易理解的地方我做了注释 祝你成功~~~
public File putOutTaskToExcelFile(List《E》 getPutOutTaskResult) {
//在我的代码里,getPutOutTaskResult是我需要导出的信息列表,你换成你的就行
BufferedWriter out = null;
int random = (int) (Math.random() * 1000 + 1);
//这个随机数只是为了让后面生成的文件名不重复而已
File excelFile = null;
try {
excelFile = File.createTempFile("你的文件名" + random,".csv");
//生成一个csv临时文件
excelFile.deleteOnExit();
} catch (IOException e1) {
e1.printStackTrace();
}
int i = 1;
try {
out = new BufferedWriter(new FileWriter(excelFile));
out
.write("序号" + "," + "用户号码" + "," + "是否成功" + "," + "失败原因"
+ ",");//换成你需要的表头
out.newLine();
Iterator《E》 resultIterator = getPutOutTaskResult.iterator();
while (resultIterator.hasNext()) {
E e = resultIterator.next();
out.write(i + "," + A + ","
+ B + "," + C);
//A、B、C等等都换上你自己的就可以 i是一个自增序号
out.newLine();
i++;
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return excelFile;
}
/**
* 将服务器端生成的Excel文件提供给客户端下载
*
* @param request
* @param response
* @param tempFile
*/
private void download(HttpServletRequest request,
HttpServletResponse response, File tempFile) {
String filenamedownload = tempFile.toString();
String filenamedisplay = tempFile.getName();
try {
filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
response.addHeader("Content-Disposition", "attachment;filename="
+ filenamedisplay);
OutputStream output = null;
FileInputStream fis = null;
try {
output = response.getOutputStream();
fis = new FileInputStream(filenamedownload);
byte;
int i = 0;
while ((i = fis.read(b)) 》 0) {
output.write(b, 0, i);
}
output.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
fis = null;
}
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
output = null;
}
}
}
java 如何给pdf文件加水印
Java生成PDF 加密 水印
1、iText简介
***隐藏网址***
下载最新版本的类库,下载完成之后会得到一个.jar包,把这个包加入JDK的classpath即可使用。
***隐藏网址***
下载iTextAsian.jar包。
***隐藏网址***
有比较详细的教程。该教程从入门开始,比较系统地介绍了在PDF文件中放入文字、图片、表格等的方法和技巧。
读完这片教程,大致就可以做一些从简单到复杂的PDF文件了。不过,试图通过教程解决在生成PDF文件过程中遇到的所有困难无疑是一种奢望。所以,阅读iText的api文档显得非常重要。读者在下载类库的同时,也可以下载类库的文档。
注:如果以上两个下载链接无法下载而且通过网络也找不到这个jar包的同志可以留下邮箱地址,我会在两个工作日之内发邮件过去。
以下部分我是我调试通过的源代码,提供大家参考:
import java.awt.*;
import java.io.*;
import com.lowagie.text.*;
import com.lowagie.text.Font;
import
com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.*;
/**
* 最近的项目中使用Itext将txt文件转换为PDF文件, 并且实现对文件的一些权限控制。
现实对pdf文件加
*密,添加水印等。
*/
public class PDFConvertBL
{
//
txt原始文件的路径
private static final String txtFilePath = "d:/11.txt";
// 生成的pdf文件路径
private static final String pdfFilePath =
"d:/22.pdf";
// 添加水印图片路径
// private static final String
imageFilePath = "D:/33.jpg";
// 生成临时文件前缀
private static final
String prefix = "tempFile";
// 所有者密码
private static final String
OWNERPASSWORD = "12345678";
/**
* txt文件转换为pdf文件
*
* @param txtFile
txt文件路径
* @param pdfFile pdf文件路径
* @param userPassWord
用户密码
* @param waterMarkName 水印内容
* @param permission
操作权限
*/
public static void generatePDFWithTxt(String txtFile,
String pdfFile, String userPassWord, String
waterMarkName,
int permission)
{
try
{
// 生成临时文件
File file =
File.createTempFile(prefix, ".pdf");
//
创建pdf文件到临时文件
if (createPDFFile(txtFile, file))
{
// 增加水印和加密
waterMark(file.getPath(),
pdfFile, userPassWord, OWNERPASSWORD, waterMarkName, permission);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 创建PDF文档
*
* @param txtFilePath
txt文件路径(源文件)
* @param pdfFilePath pdf文件路径(新文件)
*/
private
static boolean createPDFFile(String txtFilePath, File file)
{
// 设置纸张
Rectangle rect = new Rectangle(PageSize.A4);
//
设置页码
HeaderFooter footer = new HeaderFooter(new Phrase("页码:",
setChineseFont()), true);
footer.setBorder(Rectangle.NO_BORDER);
// step1
Document
doc = new Document(rect, 50, 50, 50, 50);
doc.setFooter(footer);
try
{
FileReader
fileRead = new FileReader(txtFilePath);
BufferedReader read = new
BufferedReader(fileRead);
// 设置pdf文件生成路径 step2
PdfWriter.getInstance(doc, new FileOutputStream(file));
//
打开pdf文件 step3
doc.open();
// 实例化Paragraph
获取写入pdf文件的内容,调用支持中文的方法. step4
while (read.ready())
{
// 添加内容到pdf(这里将会按照txt文件的原始样式输出)
doc.add(new Paragraph(read.readLine(), setChineseFont()));
}
// 关闭pdf文件 step5
doc.close();
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
/**
* 在pdf文件中添加水印
*
* @param inputFile
原始文件
* @param outputFile 水印输出文件
* @param waterMarkName
水印名字
*/
private static void waterMark(String inputFile, String
outputFile, String userPassWord, String ownerPassWord,
String waterMarkName, int permission)
{
try
{
PdfReader reader = new PdfReader(inputFile);
PdfStamper stamper = new PdfStamper(reader, new
FileOutputStream(outputFile));
// 设置密码
stamper.setEncryption(userPassWord.getBytes(), ownerPassWord.getBytes(),
permission, false);
BaseFont base =
BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
BaseFont.NOT_EMBEDDED);
int total = reader.getNumberOfPages() +
1;
// Image image =
Image.getInstance(imageFilePath);
//
image.setAbsolutePosition(200, 400);
PdfContentByte
under;
int j = waterMarkName.length();
char c =
0;
int rise = 0;
for (int i = 1; i 《 total;
i++)
{
rise = 500;
under =
stamper.getUnderContent(i);
// 添加图片
//
under.addImage(image);
under.beginText();
under.setColorFill(Color.CYAN);
under.setFontAndSize(base,
30);
// 设置水印文字字体倾斜 开始
if (j 》=
15)
{
under.setTextMatrix(200,
120);
for (int k = 0; k 《 j;
k++)
{
under.setTextRise(rise);
c =
waterMarkName.charAt(k);
under.showText(c +
"");
rise -= 20;
}
}
else
{
under.setTextMatrix(180, 100);
for (int k = 0; k 《 j; k++)
{
under.setTextRise(rise);
c = waterMarkName.charAt(k);
under.showText(c +
"");
rise -= 18;
}
}
// 字体设置结束
under.endText();
// 画一个圆
//
under.ellipse(250, 450, 350, 550);
//
under.setLineWidth(1f);
// under.stroke();
}
stamper.close();
}
catch (Exception
e)
{
e.printStackTrace();
}
}
/**
* 设置中文
*
* @return Font
*/
private static Font setChineseFont()
{
BaseFont base =
null;
Font fontChinese = null;
try
{
base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
BaseFont.EMBEDDED);
fontChinese = new Font(base, 12,
Font.NORMAL);
}
catch (DocumentException e)
{
e.printStackTrace();
}
catch (IOException
e)
{
e.printStackTrace();
}
return fontChinese;
}
public static void main(String args)
{
generatePDFWithTxt(txtFilePath, pdfFilePath, "123", "水印文字", 16);
}
}
文章参考一些网络博客稍加修改调试,特此申明
***隐藏网址***

更多文章:
vbnet连接sql数据库实例(请各位大侠给出用VB.NET连接oracle数据库并执行sql查询语句的代码示例,谢谢!!)
2026年7月21日 09:15
python编程实例详解(python函数变量及代码利用是什么python函数变量及代码利用说明)
2025年8月3日 06:00
已知大写字母a的ascii码值十进制(已知大写字母a的ASCII码值十进制表示为65那么asii码值为十进制数68的字母是)
2026年8月11日 21:30
struts2拦截器和过滤器的区别(struts2拦截器的作用是什么(它拦截什么)过滤器的作用是什么呢(过滤什么))
2025年6月18日 21:15
sql语句优化面试(面试问到 数据库性能优化 怎么回答 我是Oracle数据库)
2025年7月30日 02:15
commerce和commercial的区别(commercial名词)
2026年7月6日 01:00
shell脚本写加减乘除运算(用shell做个加减乘除运算)
2025年6月20日 21:30
keystone蝶阀中国代理(美国泰科TYCO阀门授权代理商)
2025年9月8日 02:45
日期型的函数datediff(datediff函数怎么用啊)
2025年12月17日 06:15
加拿大study permit(加拿大的STUDY PERMIT 里,签证官指定学校这句话什么意思 )
2026年8月7日 06:45
小米13发布会为何延期(小米和华为的冬季新品发布会为什么延期)
2026年6月3日 04:30
rank函数如何自动填充(excel根据最终得分列数据公式填充排名列数据)
2026年3月12日 12:15
rsync协议(为什么rsync服务对应的端口显示所属进程是xinetd而非rsync)
2025年11月11日 08:30
reset current branch to here(resetcurrentbranchtohere会覆盖本地代)
2025年11月13日 21:30
c语言中printf与scanf的先后顺序(c语言中printf 跟scanf执行顺序颠倒)
2026年2月26日 06:00
ASP.NET MVC 4框架揭秘:Controller类型的缓存?RxCache缓存框架
2026年6月1日 06:00
![vb 全局数组 如何在子过程里定义全局性的数组,在主函数里可以使用?在java中定义了一个二维数组,int[][] a = null;a[1] = new int[]{1,2,3};这样定义对不对](/static/images/nopic/15.jpg)










