Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Intro_Java_brief_Liang2011.pdf
Скачиваний:
195
Добавлен:
26.03.2016
Размер:
10.44 Mб
Скачать

320 Chapter 9 Strings and Text I/O

Enter a string: ab<c>cb?a Ignoring nonalphanumeric characters, is ab<c>cb?a a palindrome? true

Enter a string: abcc><?cab Ignoring nonalphanumeric characters, is abcc><?cab a palindrome? false

The filter(String s) method (lines 31–44) examines each character in string s and copies it to a string builder if the character is a letter or a numeric character. The filter method returns the string in the builder. The reverse(String s) method (lines 47–52) creates a new string that reverses the specified string s. The filter and reverse methods both return a new string. The original string is not changed.

The program in Listing 9.1 checks whether a string is a palindrome by comparing pairs of characters from both ends of the string. Listing 9.4 uses the reverse method in the StringBuilder class to reverse the string, then compares whether the two strings are equal to determine whether the original string is a palindrome.

9.5 Command-Line Arguments

Perhaps you have already noticed the unusual declarations for the main method, which has parameter args of String[] type. It is clear that args is an array of strings. The main method is just like a regular method with a parameter. You can call a regular method by passing actual parameters. Can you pass arguments to main? Yes, of course you can. For example, the main method in class TestMain is invoked by a method in A, as shown below:

public class A {

 

public class TestMain {

public static void main(String[] args) {

 

 

public static void main(String[] args)

{

String[] strings = {"New York",

 

 

for (int i = 0; i < args.length; i++)

 

 

"Boston", "Atlanta"};

 

 

System.out.println(args[i]);

 

TestMain.main(strings);

 

 

}

 

}

 

 

 

}

 

 

}

 

 

 

 

 

 

 

 

 

 

 

 

 

A main method is just a regular method. Furthermore, you can pass arguments from the command line.

9.5.1Passing Strings to the main Method

You can pass strings to a main method from the command line when you run the program. The following command line, for example, starts the program TestMain with three strings: arg0, arg1, and arg2:

java TestMain arg0 arg1 arg2

arg0, arg1, and arg2 are strings, but they don’t have to appear in double quotes on the command line. The strings are separated by a space. A string that contains a space must be enclosed in double quotes. Consider the following command line:

java TestMain "First num" alpha 53

It starts the program with three strings: "First num", alpha, and 53, a numeric string. Since "First num" is a string, it is enclosed in double quotes. Note that 53 is actually treated as a string. You can use "53" instead of 53 in the command line.

9.5 Command-Line Arguments 321

When the main method is invoked, the Java interpreter creates an array to hold the com- mand-line arguments and pass the array reference to args. For example, if you invoke a program with n arguments, the Java interpreter creates an array like this one:

args = new String[n];

The Java interpreter then passes args to invoke the main method.

Note

If you run the program with no strings passed, the array is created with new String[0]. In this case, the array is empty with length 0. args references to this empty array. Therefore, args is not null, but args.length is 0.

9.5.2Problem: Calculator

Suppose you are to develop a program that performs arithmetic operations on integers. The program receives three arguments: an integer followed by an operator and another integer. For example, to add two integers, use this command:

java Calculator 2 + 3

The program will display the following output:

2 + 3 = 5

Figure 9.14 shows sample runs of the program.

Add

Subtract

Multiply

Divide

Video Note

Command-line argument

FIGURE 9.14 The program takes three arguments (operand1 operator operand2) from the command line and displays the expression and the result of the arithmetic operation.

The strings passed to the main program are stored in args, which is an array of strings. The first string is stored in args[0], and args.length is the number of strings passed.

Here are the steps in the program:

Use args.length to determine whether three arguments have been provided in the command line. If not, terminate the program using System.exit(0).

Perform a binary arithmetic operation on the operands args[0] and args[2] using the operator specified in args[1].

The program is shown in Listing 9.5.

LISTING 9.5 Calculator.java

1 public class Calculator {

2/** Main method */

3 public static void main(String[] args) {

322 Chapter 9

Strings and Text I/O

 

4

// Check number of strings passed

 

5

if

(args.length

!= 3) {

 

6

System.out.println(

 

7

 

"Usage: java Calculator operand1 operator operand2");

 

8

System.exit(0);

 

9

}

 

 

 

 

 

 

 

 

 

 

 

 

10

 

 

 

 

 

 

 

 

 

 

 

 

 

11

// The result of the operation

 

12

int result = 0;

 

13

 

 

 

 

 

 

 

 

 

 

 

 

 

14

// Determine the operator

check operator

15

switch

(args[1].charAt(0)

) {

 

16

case '+': result = Integer.parseInt(args[

0]) +

 

17

 

 

 

 

Integer.parseInt(args[

2]

);

 

18

 

 

break;

 

19

case '-': result = Integer.parseInt(args[

0]

) -

 

20

 

 

 

 

Integer.parseInt(args[

2]

);

 

21

 

 

break;

 

22

case '*': result = Integer.parseInt(args[

0]

) *

 

23

 

 

 

 

Integer.parseInt(args[

2]

);

 

24

 

 

break;

 

25

case '/': result = Integer.parseInt(args[

0]

) /

 

26

 

 

 

 

Integer.parseInt(args[

2]

);

 

27

}

 

 

 

 

 

 

 

 

 

 

 

 

28

 

 

 

 

 

 

 

 

 

 

 

 

 

29

// Display result

 

30

System.out.println(args[

0]

+ ' ' +

args[1]

+ ' ' +

args[2]

 

31

+ " = " + result);

 

32

}

 

 

 

 

 

 

 

 

 

 

 

 

33

}

 

 

 

 

 

 

 

 

 

 

 

Integer.parseInt(args[0]) (line 16) converts a digital string into an integer. The string must consist of digits. If not, the program will terminate abnormally.

 

Note

special * character

In the sample run, "*" had to be used instead of * for the command

java Calculator 63 "*" 40

The * symbol refers to all the files in the current directory when it is used on a command line. Therefore, in order to specify the multiplication operator, the * must be enclosed in quote marks in the command line. The following program displays all the files in the current directory when issuing the command java Test *:

public class Test {

public static void main(String[] args) { for (int i = 0; i < args.length; i++)

System.out.println(args[i]);

}

}

9.6 The File Class

Data stored in variables, arrays, and objects are temporary; they are lost when the program terminates. To permanently store the data created in a program, you need to save them in a file on a disk or a CD. The file can be transported and can be read later by other programs. Since

why file? data are stored in files, this section introduces how to use the File class to obtain file properties and to delete and rename files. The next section introduces how to read/write data from/to text files.

9.6 The File Class 323

Every file is placed in a directory in the file system. An absolute file name contains a file name with its complete path and drive letter. For example, c:\book\Welcome.java is the absolute file name for the file Welcome.java on the Windows operating system. Here c:\book is referred to as the directory path for the file. Absolute file names are machine dependent. On the Unix platform, the absolute file name may be /home/liang/book/Welcome.java, where /home/liang/book is the directory path for the file Welcome.java.

The File class is intended to provide an abstraction that deals with most of the machinedependent complexities of files and path names in a machine-independent fashion. The File class contains the methods for obtaining file properties and for renaming and deleting files, as shown in Figure 9.15. However, the File class does not contain the methods for reading and writing file contents.

absolute file name

directory path

java.io.File

 

 

 

 

 

+File(pathname: String)

 

Creates a File object for the specified path name. The path name may be a

 

 

directory or a file.

+File(parent: String, child: String)

 

Creates a File object for the child under the directory parent. The child may be

 

 

a file name or a subdirectory.

+File(parent: File, child: String)

 

Creates a File object for the child under the directory parent. The parent is a

 

 

File object. In the preceding constructor, the parent is a string.

+exists(): boolean

 

Returns true if the file or the directory represented by the File object exists.

+canRead(): boolean

 

Returns true if the file represented by the File object exists and can be read.

+canWrite(): boolean

 

Returns true if the file represented by the File object exists and can be written.

+isDirectory(): boolean

 

Returns true if the File object represents a directory.

+isFile(): boolean

 

Returns true if the File object represents a file.

+isAbsolute(): boolean

 

Returns true if the File object is created using an absolute path name.

+isHidden(): boolean

 

Returns true if the file represented in the File object is hidden. The exact

 

 

definition of hidden is system dependent. On Windows, you can mark a file

 

 

hidden in the File Properties dialog box. On Unix systems, a file is hidden if

 

 

its name begins with a period character '.'.

+getAbsolutePath(): String

 

Returns the complete absolute file or directory name represented by the File

 

 

object.

+getCanonicalPath(): String

 

Returns the same as getAbsolutePath() except that it removes redundant

 

 

names, such as "." and "..", from the path name, resolves symbolic links (on

 

 

Unix platforms), and converts drive letters to standard uppercase (on Win32

 

 

platforms).

+getName(): String

 

Returns the last name of the complete directory and file name represented by

 

 

the File object. For example, new File("c:\\book\\test.dat").getName() returns

 

 

test.dat.

+getPath(): String

 

Returns the complete directory and file name represented by the File object.

 

 

For example, new File("c:\\book\\test.dat").getPath() returns c:\book\test.dat.

+getParent(): String

 

Returns the complete parent directory of the current directory or the file

 

 

represented by the File object. For example, new

 

 

File("c:\\book\\test.dat").getParent() returns c:\book.

+lastModified(): long

 

Returns the time that the file was last modified.

+length(): long

 

Returns the size of the file, or 0 if it does not exist or if it is a directory.

+listFile(): File[]

 

Returns the files under the directory for a directory File object.

+delete(): boolean

 

Deletes this file. The method returns true if the deletion succeeds.

+renameTo(dest: File): boolean

 

Renames this file. The method returns true if the operation succeeds.

 

 

 

FIGURE 9.15 The File class can be used to obtain file and directory properties and to delete and rename files.

The file name is a string. The File class is a wrapper class for the file name and its directory path. For example, new File("c:\\book") creates a File object for the directory c:\book, and new File("c:\\book\\test.dat") creates a File object for the file c:\\book\\test.dat, both on Windows. You can use the File class’s isDirectory() method to check whether the object represents a directory, and the isFile() method to check whether the object represents a file.

Caution

The directory separator for Windows is a backslash (\). The backslash is a special character in

 

Java and should be written as \\ in a string literal (see Table 2.6).

\ in file names

324 Chapter 9 Strings and Text I/O

Note

Constructing a File instance does not create a file on the machine. You can create a File instance for any file name regardless whether it exists or not. You can invoke the exists() method on a File instance to check whether the file exists.

 

Do not use absolute file names in your program. If you use a file name such as

 

"c:\\book\\Welcome.java", it will work on Windows but not on other platforms. You

relative file name

should use a file name relative to the current directory. For example, you may create a File

 

object using new File("Welcome.java") for the file Welcome.java in the current direc-

 

tory. You may create a File object using new File("image/us.gif") for the file us.gif

Java directory separator (/)

under the image directory in the current directory. The forward slash (/) is the Java directory

 

separator, which is the same as on Unix. The statement new File("image/us.gif") works

 

on Windows, Unix, and any other platform.

 

Listing 9.6 demonstrates how to create a File object and use the methods in the File

 

class to obtain its properties. The program creates a File object for the file us.gif. This file is

 

stored under the image directory in the current directory.

LISTING 9.6 TestFileClass.java

 

1

public class TestFileClass {

 

2

public static void main(String[] args) {

create a File

3

 

java.io.File file = new java.io.File("image/us.gif");

 

exists()

4

 

System.out.println("Does it exist? " +

file.exists()

);

length()

5

 

System.out.println("The file has " + file.length() + " bytes");

canRead()

6

 

System.out.println("Can it be read? " + file.canRead());

canWrite()

7

 

System.out.println("Can it be written? " + file.canWrite());

isDirectory()

8

 

System.out.println("Is it a directory? " + file.isDirectory());

isFile()

9

 

System.out.println("Is it a file? " + file.isFile());

isAbsolute()

10

 

System.out.println("Is it absolute? " + file.isAbsolute());

isHidden()

11

 

System.out.println("Is it hidden? " + file.isHidden());

 

12

 

System.out.println("Absolute path is " +

getAbsolutePath()

13

 

file.getAbsolutePath());

 

14

 

System.out.println("Last modified on " +

lastModified()

15

 

new java.util.Date(file.lastModified()));

 

16

}

 

 

 

 

 

17

}

 

 

 

 

The lastModified() method returns the date and time when the file was last modified, measured in milliseconds since the beginning of Unix time (00:00:00 GMT, January 1, 1970). The Date class is used to display it in a readable format in lines 14–15.

(a) On Windows

(b) On Unix

FIGURE 9.16 The program creates a File object and displays file properties.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]