龙空技术网

Java|输入输出:字符入,字符出,中间按类型解析与处理

小智雅汇 76

前言:

现时我们对“java输入输出”大体比较珍视,咱们都需要知道一些“java输入输出”的相关内容。那么小编同时在网络上收集了一些有关“java输入输出””的相关文章,希望各位老铁们能喜欢,看官们一起来学习一下吧!

The keyboard sends character data to the computer, even when the characters look like numbers. And the program sends characters to the monitor, even when it has calculated a numerical result. (Actually, characters are not sent directly to the monitor. They are sent to the graphics card which converts them into a video signal which is displayed on the monitor.)

键盘向计算机发送字符数据,即使字符看起来像数字。程序向监视器发送字符,即使它已经计算了一个数值结果。(实际上,字符不是直接发送到显示器的,而是发送到图形卡,图形卡将字符转换成视频信号,并显示在显示器上。)

If your program does arithmetic, the input characters must be converted into one of the primitive numeric data types. This is done using a Scanner object. Then a result is calculated using arithmetic with the numeric data. The result must then converted into character data before it is sent to the monitor. This is done using a method of System.out.

如果程序执行算术运算,则必须将输入字符转换为一种基本的数字数据类型。这是使用Scanner对象完成的。然后,使用算术和数值数据计算结果。然后,在将结果发送到监视器之前,必须将其转换为字符数据。这是通过使用System.out来实现的。

Here is a picture of a Java program doing character input and output. In this picture, the white box represents the entire program. The program has imported Scanner for use with input, and has imported System.out for use with output.

上面是一个Java程序进行字符输入和输出的图片。在这张图中,白框代表整个程序。该程序已导入Scanner用于输入,并已导入System.out用于输出。

To use the methods of a Scanner an object must be constructed. (The diagram shows the object as a rectangle.)

要使用Scanner的方法,必须构造一个对象。(该图将对象显示为矩形。)

The nextLine() method of Scanner reads one line of character data from the keyboard. The characters go into a String object. An assignment statement puts a reference to the object in the reference variable inData. To output the characters to the monitor, the program uses the println() method of System.out.

1 nextLine()

Scanner的nextLine()方法从键盘读取一行字符数据。这些字符进入字符串对象。赋值语句将对象的引用放入引用变量inData中。为了将字符输出到监视器,程序使用System.out的println()方法。

2 nextInt()

The nextInt() method of a Scanner object reads in a string of digits (characters) and converts them into an int type.

Scanner对象的nextInt()方法读取一串数字(字符),并将其转换为int类型。

The Scanner object reads the characters one by one until it has collected those that are used for one integer. Then it converts them into a 32-bit numeric value. Usually that value is stored in an int variable.

Scanner对象逐个读取字符,直到收集了用于一个整数的字符。然后将其转换为32位数值。通常,该值存储在int变量中。

The picture shows a program that reads in character data and then converts it into an integer which is stored in num. Next the program does arithmetic with num and stores the result in square. Finally the result is sent to println which converts the numeric result into characters and prints them out.

图中显示了一个程序,该程序读取字符数据,然后将其转换为存储在num中的整数。接下来,该程序对num进行算术运算,并将结果存储为平方。最后,结果被发送到println,println将数字结果转换为字符并打印出来。

The nextInt() method scans through the input stream character by character, gathering characters into a group that can be converted into numeric data. It ignores spaces and end-of-lines that may preceed the group.

nextInt()方法逐个字符扫描输入流,将字符收集到可以转换为数字数据的组中。它设计为忽略可能位于组前面的空格和行尾。

A space or end-of-line charater that follows a string of digits ends the group. A non-digit character cannot be part of a group (not even at the end.).

字符串后面的空格或行尾字符是组的结尾。非数字字符不能是组的一部分(甚至不能在末尾)。

import java.util.Scanner;public class EchoSquare{    public static void main (String[] args)    {        Scanner scan = new Scanner( System.in );        int num, square;      // declare two int variables        System.out.println("Enter an integer:");        num = scan.nextInt();        square = num * num ;  // compute the square        System.out.println("The square of " + num + " is " + square);    }}

Here is a statement from the program:

num = scan.nextInt();

Assignment statements work in two steps:

赋值语句分为两个步骤:

Evaluate the expression on the right of the equal sign,

计算等号右边的表达式,

Put the value into the variable on the left.

将值放入左边的变量中。

In this particular assignment statement, the expression on the right scans a group of characters from the input stream and converts them into an int, if that is possible. Then the numeric result is stored into num.

在这个特定的赋值语句中,右边的表达式扫描输入流中的一组字符,并将它们转换为int(如果可能的话)。然后将数值结果存储到num中。

If the group of characters cannot be converted, Java throws an Exception and stops your program. An Exception object contains information about what went wrong in a program. Industrial-strength programs may examine the exception and try to fix the problem. Our programs (for now) will just stop.

如果无法转换字符组,Java会抛出异常并停止程序。异常对象包含程序中出错的信息。工业实用项目可能会检查例外情况,并试图解决问题。我们的项目(目前)将停止。

3 printf()

System.out.printf(Locale.CHINA, "PI =%8.4f%n", Math.PI); // 8 places, 4 for precision

The format string describes the desired format. The characters in the string are printed out as given until a format specifier is encountered. This describes how a value is to be printed.

格式字符串描述了所需的格式。字符串中的字符将按给定的格式打印出来,直到遇到格式说明符。这描述了如何打印值。

conversion code:

Conversion Code

Type

Example Output

b

boolean

true

c

character

B

d

integer (output as decimal)

221

o

integer (output as octal)

335

x

integer (output as hex)

dd

f

floating point

45.356

e

floating point (scientific notation)

-8.756e+05

s

String

Hello World

n

newline

4 File IO and checked IOException

Input and output are especially error prone. Exception handling is essential for I/O programming.

输入和输出尤其容易出错。异常处理对于I/O编程至关重要。

An exception is a problem that occurs when a program is running. Often the problem is external to the program, such as bad user input, or mechanical failure of an I/O device. When an exception occurs, the Java virtual machine creates an object of class Exception which holds information about the problem.

异常是程序运行时发生的问题。问题通常是程序外部的,例如用户输入错误或输入/输出设备的机械故障。当异常发生时,Java虚拟机创建一个Exception类的对象,该对象保存有关问题的信息。

IOException is a checked exception. Some programs use the readLine() method of BufferedReader for input. This method throws an IOException when there is a problem reading. Programs that use BufferedReader for input need to do something about possible exceptions.

IOException是checked exception。有些程序使用BufferedReader的readLine()方法进行输入。当读取出现问题时,此方法引发IOException。使用BufferedReader进行输入的程序需要对可能的异常进行处理。

Scanner may also be connected to a disk file. Characters from the file are put into a stream one after another.

Scanner也可以连接到磁盘文件。文件中的字符一个接一个地放入流中。

For checked Exceptions, a method must either declare that it throws the Exception, or it must catch the Exception.

对于checked Exceptions,方法必须声明抛出异常,或者必须捕获异常。

Below program catches both Exception types that might arise. If both the creation of the Scanner and the execution of scan.nextInt() worked, then the square of the number is printed out and neither catch block is executed.

以下程序捕获可能出现的两种异常类型。如果同时创建Scanner和scan.nextInt(),然后输出数字的平方,并且不执行任何catch块。

import java.util.*;import java.io.*;public class EchoSquareException{    public static void main (String[] args)    {        int num, square;        Scanner scan = null;                try        {            File file = new File("myData.txt"); // create a File object            scan = new Scanner( file );      // connect a Scanner to the file            num = scan.nextInt();  // read and convert the first token            square = num * num ;            System.out.println("The square of " + num + " is " + square);        }        catch ( IOException iox )        {            System.out.println("Error opening the file");        }        catch ( InputMismatchException imx )        {            System.out.println("Bad data in the file");        }        if( scan != null ) scan.close();        System.out.println("Good-bye");    }}

关于异常的一些设计哲学:

① 异常本就应该是函数签名的一部分,就像函数的返回类型一样。

② Java 的异常并不全是 Checked Exception,RuntimeException 并不是 Checked。

③ 异常不应该被用来传递程序逻辑的 Bug,比如空指针解引用。

④ 在一个函数的调用处,并没有显式地说明某个函数调用是否会抛出异常。大部分情况下都是一个try 包住很多可能发生异常的函数调用,处理方式太过于粗粒度,也不利于 Code Review。

⑤ Java 并没有鼓励“单一失败模式”(即 throws Exception)。有些时候,多失败模式是有必要的,但多数情况下,程序的恢复处理逻辑与具体发生了什么错误无关(即只需要直知道成功与否即可)。当与具体发生的错误有关时,作者推荐使用 “The Keeper Pattern”。

⑥ 相比于 Checked Exception,Unchecked Exception 可靠性更低,它需要以文档的方式说明一个函数可能会抛出什么异常,对程序员、IDE、编译器都不友好。但正如 Andrew 在一篇采访 The Trouble with Checked Exceptions 中所说,在某些时候(比如应用开发),大多数人并不关心如何处理异常,他们只关心当异常发生时我要处理好后事(C# 的 using),剩下的事就交给最上层的 catch 去做好了。这是大家喜欢 Unchecked Exception 的原因。

Java中有两种异常:受检查的(checked)异常和不受检查的(unchecked)异常。不受检查的异常不需要在方法或者是构造函数上声明,就算方法或者是构造函数的执行可能会抛出这样的异常,并且不受检查的异常可以传播到方法或者是构造函数的外面。相反,受检查的异常必须要用throws语句在方法或者是构造函数上声明。

5 OutputStream(binary file)

import java.io.*;class WriteInts{    public static void main ( String[] args )    {        String fileName = "intData.dat" ;                try        {            DataOutputStream out = new DataOutputStream(            new BufferedOutputStream(            new FileOutputStream( fileName )));                        for( int j=0; j<512; j++ )                out.writeInt( j );                        out.close();        }        catch ( IOException iox )        {            System.out.println("Problem writing " + fileName );        }    }}
6 DataInputStream
import java.io.*;class ReadInts{    public static void main ( String[] args )    {        String fileName = "intData.dat" ;        long sum = 0;                try        {            DataInputStream instr =            new DataInputStream(            new BufferedInputStream(            new FileInputStream( fileName ) ) );                        sum += instr.readInt();            sum += instr.readInt();            sum += instr.readInt();            sum += instr.readInt();                        System.out.println( "The sum is: " + sum );            instr.close();        }        catch ( IOException iox )        {            System.out.println("Problem reading " + fileName );        }    }}

7 文件复制

import java.io.*;class CopyBytes{  public static void main ( String[] args )   {    DataInputStream  instr;    DataOutputStream outstr;    if ( args.length != 3 || !args[1].toUpperCase().equals("TO") )    {      System.out.println("java CopyBytes source to destination");      return;    }    File inFile  = new File( args[0] );    File outFile = new File( args[2] );    if ( outFile.exists() )    {      System.out.println( args[2] + " already exists");      return;    }    if ( !inFile.exists() )    {      System.out.println( args[0] + " does not exist");      return;    }    try    {      instr =         new DataInputStream(          new BufferedInputStream(            new FileInputStream( inFile )));      outstr =         new DataOutputStream(          new BufferedOutputStream(            new FileOutputStream( outFile  )));      try      {        int data;        while ( true )        {          data = instr.readUnsignedByte() ;          outstr.writeByte( data ) ;        }      }      catch ( EOFException  eof )      {        outstr.close();        instr.close();        return;      }    }    catch ( FileNotFoundException nfx )    {      System.out.println("Problem opening files" );    }    catch ( IOException iox )    {      System.out.println("I/O Problems" );    }  }}

-End-

标签: #java输入输出 #java中如何输入一个数据 #java输入和输出数据的形式 #用java输出 #java的符号怎么打