URL url = new URL("http://example.com"); Object content = url.getContent(); if (content instanceof InputStream) { BufferedReader in = new BufferedReader(new InputStreamReader((InputStream) content)); String line; while ((line = in.readLine()) != null) { System.out.println(line); } in.close(); }
URL url = new URL("file:///path/to/file.txt"); Object content = url.getContent(); if (content instanceof InputStream) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[1024]; while ((nRead = ((InputStream) content).read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); byte[] bytes = buffer.toByteArray(); System.out.println(Arrays.toString(bytes)); }This example retrieves the content of a file at /path/to/file.txt and prints it as an array of bytes. In both examples, the java.net package library is used.