在Java中如何下载/导出.txt文件?

3

我在控制器中形成了一个url。当我访问该url时,需要导出一个.txt文件。由于我对这个概念还很陌生,所以有一些疑问:

1)我们是否需要像添加pdf和xls的jar文件一样导入任何jar文件来导出.txt文件?

我尝试了以下代码...但是我没有得到任何结果。我没有添加任何jar文件...

FileWriter writer = new FileWriter("MyFile.txt", true);
        writer.write("Hello World");
        writer.write("\r\n");   // write new line
        writer.write("Good Bye!");
        writer.close();

你的意思是你想要下载这个文件吗? - androidGenX
是的,我需要下载。 - Bhanu
你是使用servlet还是纯Java? - androidGenX
使用Servlets也可以。 - Bhanu
1
尝试一下这个,但它有详细的解释:http://www.codejava.net/java-ee/servlet/java-servlet-download-file-example - androidGenX
显示剩余3条评论
2个回答

3

在我的几个项目中,我使用了来自codejava.net的这个实用类。

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * A utility that downloads a file from a URL.
 * @author www.codejava.net
 *
 */
public class HttpDownloadUtility {
    private static final int BUFFER_SIZE = 4096;


        /**
         * Downloads a file from a URL
         * @param fileURL HTTP URL of the file to be downloaded
         * @param saveDir path of the directory to save the file
         * @throws IOException
         */
        public static void downloadFile(String fileURL, String saveDir)
                throws IOException {
            URL url = new URL(fileURL);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            int responseCode = httpConn.getResponseCode();

            // always check HTTP response code first
            if (responseCode == HttpURLConnection.HTTP_OK) {
                String fileName = "";
                String disposition = httpConn.getHeaderField("Content-Disposition");
                String contentType = httpConn.getContentType();
                int contentLength = httpConn.getContentLength();

                if (disposition != null) {
                    // extracts file name from header field
                    int index = disposition.indexOf("filename=");
                    if (index > 0) {
                        fileName = disposition.substring(index + 10,
                                disposition.length() - 1);
                    }
                } else {
                    // extracts file name from URL
                    fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
                            fileURL.length());
                }

                System.out.println("Content-Type = " + contentType);
                System.out.println("Content-Disposition = " + disposition);
                System.out.println("Content-Length = " + contentLength);
                System.out.println("fileName = " + fileName);

                // opens input stream from the HTTP connection
                InputStream inputStream = httpConn.getInputStream();
                String saveFilePath = saveDir + File.separator + fileName;

                // opens an output stream to save into file
                FileOutputStream outputStream = new FileOutputStream(saveFilePath);

                int bytesRead = -1;
                byte[] buffer = new byte[BUFFER_SIZE];
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                outputStream.close();
                inputStream.close();

                System.out.println("File downloaded");
            } else {
                System.out.println("No file to download. Server replied HTTP code: " + responseCode);
            }
            httpConn.disconnect();
        }
    }

它可以下载...但是当我们想要将一些内容写入该文件时,该怎么做呢? - Bhanu
先生,您只需要一个FileWriter/PrintWriter组合: FileWriter fw = new FileWriter(fileName) ; PrintWriter pw = new PrintWriter(fw); ... pw.println(); - Matteo Baldi
我已经根据它回答正确了,你能否通过添加将数据写入文件的访问权限来进行编辑? - Bhanu

2

我写的代码只有三行,用于下载.txt文件。

感谢大家的帮助。

我发表这个答案只是为了帮助初学者下载一个空文件。

Adding HttpServletResponse servletResponse dependency,

OutputStream out = servletResponse.getOutputStream();
String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"Report"+".txt\";");
        servletResponse.setHeader(headerKey, headerValue);

        // obtains response's output stream
        OutputStream outStream = servletResponse.getOutputStream();

        outStream.close();   

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接