有一个需求是这样的,一个活动的推广文案一直会变化,需要将前端涉及到的代码(文案内容和样式)做到可配置化,所以将前端代码上传至服务器,把对应的文件地址存入活动表中,当查询活动详情时,解析对应的url,返回活动内容
有两种方法
一种直接通过url去访问。另一种通过ftp去获取。
1、
/**
* 通过url获取文本文件内容
*
* @param urlPath urlPath
* @return {@link String}
*/
public static String getTextFile(String urlPath) {
if (urlPath == null) {
return null;
}
String text = "";
try {
URL url = new URL(urlPath);
InputStream is = url.openStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String data = br.readLine();
while (data != null) {
text += data;
data = br.readLine();
}
br.close();
isr.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return text;
}
2、
```java
/**
* ftp获取file内容
*
* @param path 路径
* @param filename 文件名
* @return {@link String}
*/
public String getfileContent(String path,String filename) {
String text = "";
FTPFile[] ftpFileArr;
try {
boolean a = ftpClient.changeWorkingDirectory(path);
ftpFileArr = ftpClient.listFiles("filename");
log.info("ftpFileArr:" + ftpFileArr.length);
for (int i = 0; i < ftpFileArr.length; i++) {
if (ftpFileArr[i].getName().equals("temp.txt")) {
InputStream inputStream = ftpClient.retrieveFileStream("temp.txt");
InputStreamReader isr = new InputStreamReader(inputStream, "utf-8");
BufferedReader br = new BufferedReader(isr);
String data = br.readLine();
while (data != null) {
text += data;
data = br.readLine();
}
inputStream.close();
isr.close();
br.close();
ftpClient.completePendingCommand();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return text;
}