gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:54:28 25 4
gpt4 key购买 nike

我在 Controller 中形成了一个 url。当我点击该 url 时,我需要导出一个 .txt 文件。由于我是这个概念的新手,我有一个疑问,

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

我试过如下..但我没有得到任何结果.我没有添加任何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();

最佳答案

在几个项目中,我使用了 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();
}
}

关于java - 如何在 java 中下载/导出 .txt 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36301905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com