JAVA Development: Working With Files
JAVA Development: Working With Files
• Byte streams are used to perform input and output for data encoded as a
sequence of 8-bit bytes
• There are many classes related to byte streams, the most frequently used ones
are: FileInputStream, FileOutputStream
Byte Streams - Example
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("C:\\wantsome\\week8\\input.txt");
out = new FileOutputStream("C:\\wantsome\\week8\\output.txt");
int c;
while ((c = in.read()) != -1) { //read one byte at a time, until input finished
out.write(c); //and write it to the output stream
}
• Character streams are used to perform input and output for sequences of 16-bit
Unicode characters
• There are many classes related to character streams, the most frequently used
ones are: FileReader, FileWriter
Example: very similar to byte streams example, the only important difference is:
in = new FileReader("C:\\wantsome\\week8\\input.txt");
out = new FileWriter("C:\\wantsome\\week8\\output.txt");
InputStreamReader in = null;
OutputStreamWriter out = null;
try {
in = new InputStreamReader(System.in);
out = new OutputStreamWriter(System.out);
} //at the end of try the resources (in,out) will be auto closed!
Note: this is the recommended way to do it, as is cleaner/safer than a simple try!
AutoCloseable - File copy example (with buffer)
Example of file copy using a bytes stream, with buffered operations (instead of one byte at a
time), and with try-with-resources:
//open zip file and create output file with try-with-resources statement
try ( ZipFile zf = new ZipFile(zipFileName);
BufferedWriter writer = Files.newBufferedWriter(outputFilePath, StandardCharsets.UTF_8)) {
Input:
Output:
method description
public int read() throws IOException Reads the specified byte of data from the InputStream.
Returns an int. Returns the next byte of data and -1 will be
returned if it's the end of the file.
public int read(byte[] r) throws IOException Reads r.length bytes from the input stream into an array.
Returns the total number of bytes read. If it is the end of the
file, -1 will be returned.
public void close() throws IOException Closes the file output stream. Releases any system
resources associated with the file.
public int available() throws IOException Gives the number of bytes that can be read from this file
input stream. Returns an int.
FileOutputStream - Methods
method description
public void write(int w) throws IOException Writes the specified byte to the output stream.
public void write(byte[] w) throws IOException Writes w.length bytes from the mentioned byte array to
the OutputStream.
public void close() throws IOException Closes the file output stream. Releases any system
resources associated with the file.
Reading files with Scanner
java.util.Scanner class can be used to read from all kinds of input streams, including files.
It has the advantage of having nice methods like: nextLine/Long/Float/.., hasNextLine/Long/Float..
- Each file (directory or regular one) is identified by its path, specified in two possible ways:
- absolute: the full path, starting with the root directory
- relative: a path relative to the current directory (=the dir where the app started, or the user
home dir, etc..)
- File path format:
- a list of file names (parent folders + the file’s name), joined by a specific separator ( ‘\’, ‘/’)
- it may use also a few special symbols, like ‘.’ (=the dir itself) and ‘..’ (=parent dir)
Filesystem - Structure
A File object represents a file on disk, and gives us access to properties and operations on it:
//String path = "C:\\dir1\\file1.txt"; //absolute, windows style
//String path = "/dir1/file1.txt"; //absolute, linux style
String path = "dir1" + File.separator + "file1.txt"; //relative, portable format!
Other methods:
canExecute(), canRead(), canWrite() - show if operation is allowed for file
list(), listFiles() - list the direct children files (if current file is a dir)
renameTo(String), delete() - renames/deletes this file
setLastModified(long), setExecutable/setWritable/setReadonly(boolean) - update properties
Creating Directories
File class contains some methods which can be used to create directories:
• mkdir() - creates a directory, returning true on success and false on failure. Failure
indicates that the path specified in the File object already exists, or that the directory
cannot be created because the entire path does not exist yet.
try {
File dir = new File("C:\\"); // create new file object
Properties files are files with a specific format, holding ‘key=value’ pairs (one per line), usually used to
hold configuration details. Java has built-in support for working with them, using the Properties class:
HTTP:
● most common protocol for web pages
● commonly used for web services as well
● built on top of TCP/IP
HTTP Requests
Note: details on each request are also visible in browsers in the developer tools/console
(F12 in Chrome, then Network tab)...
HTTP Requests
And then a list of request headers, each a pair of name and value, like:
Header-Name: some-text-value
Host: en.wikipedia.org
User-Agent: curl/7.54.0
Accept: */*
HTTP Responses
HTTP/1.1 200
Content-Type: text/html; charset=UTF-8
Content-Length: 193139
Cache-Control: max-age=0
Accept-Ranges: bytes
<!DOCTYPE html>
<html class="client-nojs" lang="en" dir="ltr">
<head>
<title>Hypertext Transfer Protocol - Wikipedia</title>
…
HTTP Responses
HTTP/1.1 200
And finally the content (e.g the actual HTML page), also called body:
<!DOCTYPE html>
<html class="client-nojs" lang="en" dir="ltr">
<head>
<title>Hypertext Transfer Protocol - Wikipedia</title>
URL
What’s an URL?
URL = Universal Resource Locator
General format:
● protocol://hostname:port/rest_of_the_url
Examples:
● http://example.com - only protocol and hostname
● https://en.wikipedia.org/wiki/HTTP - “/wiki/HTTP” is called the path
● http://google.com/search?q=java+url - “/search” is the path, “q=java+url” is the query string
java.net.URL
● Class for handling URLs and validating that a string is a valid URL
HttpURLConnection
java.net.HttpURLConnection
● Class for making HTTP requests and reading responses
● One instance per request!
import java.net.HttpURLConnection;
import java.net.URL;
String inputLine;
StringBuilder response = new StringBuilder();
System.out.println(response.toString());
}
Questions?
HTTP - Extra reading
https://www.baeldung.com/java-http-request
https://www.testingexcellence.com/http-basics/