Michael Scott
Michael Scott

Reputation: 429

Send a text file from URL directly into a scanner

I am using java and currently, I can download a text file from the internet, read that file, then send that file into a Scanner. Is it possible to skip writing it to the harddrive and send it straight into the scanner? I tried changing the code some, but it didn't work.

URL link = new URL("http://shayconcepts.com/programming/ComicDownloader/version.txt");
ReadableByteChannel rbc = Channels.newChannel(link.openStream());//Gets the html page
FileOutputStream fos = new FileOutputStream("version.txt");//Creates the output name of the output file to be saved to the computer
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
fos.close();
Scanner sc = new Scanner(new FileReader("version.txt"));

Upvotes: 0

Views: 406

Answers (1)

BalusC
BalusC

Reputation: 1108782

Yes, it is definitely possible. Just do exactly like you said: feed the from the URL obtained input stream straight into the scanner.

Scanner sc = new Scanner(link.openStream());

It has namely also a constructor taking an input stream. It accepts by the way the charset as 2nd argument, you might want to make use of it if the text file is possibly in a different character encoding than the platform default one, otherwise you might risk Mojibake.

Scanner sc = new Scanner(link.openStream(), "UTF-8");

Upvotes: 2

Related Questions