gpt4 book ai didi

java - 获取枚举的字符串值

转载 作者:行者123 更新时间:2023-12-01 10:52:17 30 4
gpt4 key购买 nike

我想制作一个程序来下载运行增益所需的一些文件。它就像一个自动下载更新的启动器。这是我的枚举:

public class Configuration {

public enum downloadFiles {
load1 ("load1.png", "https://dl.dropboxusercontent.com/u/51947680/Xenolith/load1.png"),
load2 ("load2.png", "https://dl.dropboxusercontent.com/u/51947680/Xenolith/load2.png"),
load3 ("load3.png", "https://dl.dropboxusercontent.com/u/51947680/Xenolith/load3.png");

public String fileName, URL;

private downloadFiles(String fileName, String URL) {
this.fileName = fileName;
this.URL = URL;
}

public String getFileName() {
return fileName;
}

public String getURL() {
return URL;
}

}

}

我还有一个下载文件的类,它是:

public class DownloadUtility {
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 fileName, String fileURL)
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 disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();

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 = System.getProperty("user.home") + "/Desktop" + 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();
}
}

所以我想做的是 downloadFiles 方法按顺序下载枚举中的所有文件。顺便说一句,这是一个好方法吗?如果有更好的方法,请告诉我,因为我正在尝试学习以一种简洁的方式编写java代码。

最佳答案

您可以执行以下操作:

for(Configuration.downloadFiles df : Configuration.downloadFiles.values()){
DownloadUtility.downloadFile(df.getFileName(), df.getURL());
}

关于java - 获取枚举的字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33789311/

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