📄 loadrss.java
字号:
package book.rssreader;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
public class LoadRSS {
protected String cacheDirName = "";// 保存缓存的目录名
protected long cacheTime = 0;// 缓存时间
protected boolean bCache = true;// 是否要在缓存中读取数据
String fileName = "";// 保存在缓存中的文件名
public String getRSS(String url) {
// 首先设置文件名
if (url == null || url.equals(""))
return "";
else
fileName = url.substring(url.lastIndexOf("/") + 1);
StringBuffer bf = new StringBuffer();
if (cacheDirName == null || cacheDirName.equals(""))// 如果没有设置缓存目录,则不需要在缓存中读
bCache = false;
if (bCache) {// 如果在缓存中度数据
File cacheFile = new File("C:\\" + cacheDirName, fileName);// 查找C盘下给文件
if (!cacheFile.exists()) {// 如果该文件不存在,则新建目录
bCache = false;
try {
cacheFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} else {
long interval = new Date().getTime() - cacheFile.lastModified();// 比较该文件与缓存的时间
if (interval >= cacheTime)// 如果大于或等于缓存时间,则不在缓存中读取
bCache = false;
}
}
if (bCache) {// 如果从缓存中读取
bf.append(readFromCache(url));
} else {// 如果不从缓存中读取
bf.append(readNew(url));
}
return bf.toString();
}
// 该方法读出文件的内容
public String readFromCache(String url) {
StringBuffer buffer = new StringBuffer();
File cacheFile = new File("C:\\" + cacheDirName, fileName);
try {
BufferedReader in = new BufferedReader(new FileReader(cacheFile));
String line;
while ((line = in.readLine()) != null) {
buffer.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return buffer.toString();
}
public String readNew(String url) {
StringBuffer buffer = new StringBuffer();
try {
URL u = new URL(url);// 定义URL对象
BufferedReader in = new BufferedReader(new InputStreamReader(u
.openStream()));// 获得URL对象的所输出的数据
String inputLine;
while ((inputLine = in.readLine()) != null) {
buffer.append(inputLine);
}
in.close();
writeNew(url, buffer.toString());// 些到文件中
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer.toString();
}
public void writeNew(String url, String content) {
File cacheFile = new File("C:\\" + cacheDirName, fileName);
try {
if (!cacheFile.exists())
cacheFile.createNewFile();
FileOutputStream out = new FileOutputStream(cacheFile);
byte[] b = content.getBytes();
out.write(b);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean isBCache() {
return bCache;
}
public void setBCache(boolean cache) {
bCache = cache;
}
public String getCacheDirName() {
return cacheDirName;
}
public void setCacheDirName(String cacheDirName) {
this.cacheDirName = cacheDirName;
}
public long getCacheTime() {
return cacheTime;
}
public void setCacheTime(long cacheTime) {
this.cacheTime = cacheTime;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -