java 如何在Java中将字符串转换为文件,反之亦然?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6786183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert String to File in Java and vice versa?
提问by n92
Converting String to File: I am passing a file to an action in controller
将字符串转换为文件:我将文件传递给控制器中的操作
redirect(action:"downloadFile", params:[file:temp_file])
But when I do
但是当我做
def file = params.file
file.getName();
It give me error cannot cast object 'java.lang.String' to 'java.io.File'
它给了我错误 cannot cast object 'java.lang.String' to 'java.io.File'
How to convert String
to File
?
如何转换String
为File
?
回答by Igor Artamonov
If your params.file
is a file that user're uploading, you have to use following:
如果您params.file
是用户上传的文件,则必须使用以下内容:
def file = request.getFile('file')
//where 'file' is a name of parameter, from <input type='file'/>
please read more about file upload in Grails
请阅读有关Grails 中文件上传的更多信息
If you're trying to send this file to user's browser then:
如果您尝试将此文件发送到用户的浏览器,则:
String filename = '/reports/pdfreport9090.pdf'
response.contentType = "application/pdf"
response.setHeader("Content-disposition", "filename=$filename")
File f = new File(filename)
response.outputStream << f.newInputStream()
response.outputStream.flush()