在Java中,我们可以使用 字符输出流 它有一个以追加模式打开文件的选项。Java FileWriter类用于将面向字符的数据写入文件。它是一个面向字符的类,用于Java中的文件处理。与FileOutputStream类不同,我们不需要将字符串转换为字节数组,因为它提供了一种直接写入字符串的方法。
null
注: 可以指定缓冲区大小,也可以使用默认大小。写入程序将其输出立即发送到底层字符或字节流。
让我们看看使用的构造函数 后来,我坚持这门课的惯常方法
建造师: FileWriter(文件,布尔追加):
它在附加模式下构造一个FileWriter对象。现在让我们切换到这个类的方法,这个类在这里被调用,并在将字符串追加到现有文件中起到关键作用,如下所示:
方法1: 写()
此方法写入字符串的一部分
语法:
void write(String s,int off,int len);
返回类型: 无效的
参数:
- 输入字符串
- int off
- 字符串长度
方法2:关闭()
此方法在冲洗流后关闭流。
返回类型: 无效的
实例
JAVA
// Java Program to Append a String to the // End of a File // Importing input output classes import java.io.*; // Main class class GeeksforGeeks { // Method 1 // TO append string into a file public static void appendStrToFile(String fileName, String str) { // Try block to check for exceptions try { // Open given file in append mode by creating an // object of BufferedWriter class BufferedWriter out = new BufferedWriter( new FileWriter(fileName, true )); // Writing on output stream out.write(str); // Closing the connection out.close(); } // Catch block to handle the exceptions catch (IOException e) { // Display message when exception occurs System.out.println( "exception occurred" + e); } } // Method 2 // main driver method public static void main(String[] args) throws Exception { // Creating a sample file with some random text String fileName = "Geek.txt" ; // Try block to check for exceptions try { // Again operating same operations by passing // file as // parameter to read it BufferedWriter out = new BufferedWriter( new FileWriter(fileName)); // Writing on. file out.write( "Hello World:" ); // Closing file connections out.close(); } // Catch block to handle exceptions catch (IOException e) { // Display message when error occurs System.out.println( "Exception Occurred" + e); } // Now appendinggiven str to above // created file String str = "This is GeeksforGeeks" ; // Calling the above method appendStrToFile(fileName, str); // Let us print modified file try { BufferedReader in = new BufferedReader( new FileReader( "Geek.txt" )); String mystring; // TIll there is content in string // condition holds true while ((mystring = in.readLine()) != null ) { System.out.println(mystring); } } // Catch block to handle IO exceptions catch (IOException e) { System.out.println( "Exception Occurred" + e); } } } |
输出:
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END