📜  Java中的格式化程序 ioException() 方法和示例

📅  最后修改于: 2022-05-13 01:55:00.249000             🧑  作者: Mango

Java中的格式化程序 ioException() 方法和示例

ioException()方法是Java.util.Formatter的内置方法,它返回此格式化程序的 Appendable 最后抛出的 IOException。如果目标的append()方法从不抛出 IOException,则此方法将始终返回 null。

语法

public IOException ioException()

参数:该函数不接受任何参数。

返回值:该函数返回格式化程序的可附加项最后抛出的 IOException。

下面是上述函数的实现:

方案一:

// Java program to implement
// the above function
  
import java.util.Formatter;
import java.util.Locale;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Get the string Buffer
        StringBuffer buffer
            = new StringBuffer();
  
        // Object creation
        Formatter frmt
            = new Formatter(buffer,
                            Locale.CANADA);
  
        // Format a new string
        String name = "My name is Gopal Dave";
        frmt.format("What is your name? \n%s !",
                    name);
  
        // Print the Formatted string
        System.out.println(frmt);
  
        // flushes the formatter
        frmt.flush();
        System.out.println("Flushed");
    }
}
输出:
What is your name? 
My name is Gopal Dave !
Flushed

方案二:

// Java program to implement
// the above function
  
import java.util.Formatter;
import java.util.Locale;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // Get the string Buffer
        StringBuffer buffer
            = new StringBuffer();
  
        // Object creation
        Formatter frmt
            = new Formatter(buffer,
                            Locale.CANADA);
  
        // Format a new string
        String name = "My name is Gopal Dave";
        frmt.format("What is your name? \n%s !",
                    name);
  
        System.out.println("The last exception thrown: "
                           + frmt.ioException());
  
        // Closes the format
        frmt.close();
    }
}
输出:
The last exception thrown: null
输出:
The last exception thrown: null

参考: https: Java/util/Formatter.html#flush()