Java Reference
In-Depth Information
System. out . println ( "Please enter file to be open: " );
String fileName = keyboard . next () ;
File newFile = new File(fileName);
Scanner fileHandler = new Scanner(newFile) ;
String nextLine = fineHandler . nextLine () ;
The above code asks the user to input the file name and saves it as a string. Then it
uses the file name to create a file object. Lastly, the code reads a line from the file.
When we manually specify the location of a file, we have three options.
1. No directory is specified.
File newFile = new File( "myFile.txt" );
In this case, Java searches for the file in the root directory of the project, which is
usually different from the source directory.
2. The file directory is specified using a forward slash.
File newFile = new File( "c:/documents/myFile.txt" );
This is the easiest case. Note that this syntax can be used regardless of whether
the operating system expects a forward or backward slash.
3. File directory is specified using a backward slash.
File newFile = new File( "c:\\documents\\myFile.txt" );
This is the more complicated case. In a string, a backward slash means that a
special character follows. For example,
\\
represents a single backward slash. Note that this syntax can be used regardless of
whether the operating system expects a forward or backward slash.
\
n represents a new line. The character
Although similar, reading text from a file and from the keyboard is not identical. One
can potentially keep reading from the keyboard forever. However, one can read from a
file only until the file is exhausted. This is why one can call the hasNext , hasNextInt ,
or hasNextDouble methods on a file scanner. Once you open a file, an invisible cursor is
created in the file. When you call the nextInt method, for example, the next integer is read
from the file and the cursor skips over the integer; see Figure 13.2. The hasNext methods
can be used to check if the virtual cursor has reached the end of the file and therefore there
is no more information to read.
In our case, we can just keep reading lines from the file until we reach the end of the
file. Here is the example code.
while ( fileHandler . hasNext () )
{
String line = fileHandler .nextLine() ;
System. out . println ( l ine ) ;
}
This code will simply read the file and print it to the screen line by line. The while
statement continues until the file is exhausted.
Next, let us examine the new version of the Notepad application. We have added a
menu item that can be used to open a file. When a file is opened, the content of the file is
appended to the text area using the append method.
 
Search WWH ::




Custom Search