prevent resource leak by using try-with-resource syntax

This commit is contained in:
hrj 2020-07-03 22:20:30 +05:30
parent 300ff3162d
commit 3d147950a4

View File

@ -1396,8 +1396,10 @@ public class HTTPServer {
* Returns the body in a String format * Returns the body in a String format
*/ */
public String getJson() { public String getJson() {
java.util.Scanner s = new java.util.Scanner(body).useDelimiter("\\A"); try(final java.util.Scanner s = new java.util.Scanner(body).useDelimiter("\\A")) {
return s.hasNext() ? s.next() : ""; final String result = s.hasNext() ? s.next() : "";
return result;
}
} }
/** /**
@ -3034,15 +3036,12 @@ public class HTTPServer {
w = name.length(); w = name.length();
w += 2; // with room for added slash and space w += 2; // with room for added slash and space
// note: we use apache's format, for consistent user experience // note: we use apache's format, for consistent user experience
Formatter f = new Formatter(Locale.US); try(Formatter f = new Formatter(Locale.US)) {
f.format("<!DOCTYPE html>%n" + f.format("<!DOCTYPE html>%n" + "<html><head><title>Index of %s</title></head>%n"
"<html><head><title>Index of %s</title></head>%n" + + "<body><h1>Index of %s</h1>%n" + "<pre> Name%" + (w - 5) + "s Last modified Size<hr>", path,
"<body><h1>Index of %s</h1>%n" + path, "");
"<pre> Name%" + (w - 5) + "s Last modified Size<hr>",
path, path, "");
if (path.length() > 1) // add parent link if not root path if (path.length() > 1) // add parent link if not root path
f.format(" <a href=\"%s/\">Parent Directory</a>%" f.format(" <a href=\"%s/\">Parent Directory</a>%" + (w + 5) + "s-%n", getParentPath(path), "");
+ (w + 5) + "s-%n", getParentPath(path), "");
for (File file : dir.listFiles()) { for (File file : dir.listFiles()) {
try { try {
String name = file.getName() + (file.isDirectory() ? "/" : ""); String name = file.getName() + (file.isDirectory() ? "/" : "");
@ -3050,14 +3049,15 @@ public class HTTPServer {
// properly url-encode the link // properly url-encode the link
String link = new URI(null, path + name, null).toASCIIString(); String link = new URI(null, path + name, null).toASCIIString();
if (!file.isHidden() && !name.startsWith(".")) if (!file.isHidden() && !name.startsWith("."))
f.format(" <a href=\"%s\">%s</a>%-" + (w - name.length()) + f.format(" <a href=\"%s\">%s</a>%-" + (w - name.length()) + "s&#8206;%td-%<tb-%<tY %<tR%6s%n",
"s&#8206;%td-%<tb-%<tY %<tR%6s%n",
link, name, "", file.lastModified(), size); link, name, "", file.lastModified(), size);
} catch (URISyntaxException ignore) {} } catch (URISyntaxException ignore) {
}
} }
f.format("</pre></body></html>"); f.format("</pre></body></html>");
return f.toString(); return f.toString();
} }
}
/** /**
* Starts a stand-alone HTTP server, serving files from disk. * Starts a stand-alone HTTP server, serving files from disk.