This is my first experiment that uses a network API and connects to the internet. I tried to write a program that gives you an article of wikipedia directly by typing the name.
You can get an article like this:
java ArticleSupplier computer science
java ArticleSupplier captain underpants
If you have tips for me how to improve the performance or how to make a better structure, I would be thankful!
import java.util.Scanner;
import java.io.InputStream;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;
public class ArticleSupplier {
private String nameOfArticle; // will be the name of the created document
private String urlName;
private URL url;
private String article;
public ArticleSupplier(String[] urlComponents) {
// initialize article
article = "";
// initialize urlName and nameOfArticle
urlName = "https://en.wikipedia.org/wiki/";
nameOfArticle = "";
for(int i = 0; i < urlComponents.length; i++) {
urlName += urlComponents[i];
urlName += "_";
nameOfArticle += urlComponents[i];
nameOfArticle += " ";
}
urlName = urlName.substring(0, urlName.length() - 1);
nameOfArticle = nameOfArticle.substring(0, nameOfArticle.length() - 1);
// initialize url
try {
url = new URL(urlName);
} catch(MalformedURLException e) {
e.printStackTrace();
}
}
public void getArticle() {
try(InputStream inputStream = url.openStream(); Scanner scanner = new Scanner(inputStream)) {
while(scanner.hasNext()) {
article += scanner.next() + "\n";
}
} catch(IOException e) {
System.out.println(e);
}
}
public void saveAsHTML() {
String filename = nameOfArticle + ".html";
try(FileWriter fileWriter = new FileWriter(filename);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
bufferedWriter.write(article);
} catch(IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ArticleSupplier as = new ArticleSupplier(args);
as.getArticle();
as.saveAsHTML();
}
}
main
at the end of a source listing is older Pascal style and looks a bit odd in Java. (And we only did that because older compilers couldn't handle forward references.) \$\endgroup\$Scanner
which uses regex under the hood is going to be somewhat inefficient. Look at just using aBufferedReader
directly. Also look at setting the buffer size to something large, like 64k bytes. However, Wikipedia articles tend to be somewhat short (like, less than 1 megabyte) and so the actual performance of reading a network socket may not matter much here. (Sorry for the short comments, I don't have a lot of time atm.) \$\endgroup\$