Java BufferedWriter.write()方法

原文:https://www.studytonight.com/java-file-io/java-bufferedwriter-write-method

在本教程中,我们将从 Java 中的BufferedWriter 类中学习write()方法。此方法用于将数据写入缓冲区写入器。这个方法有三种重载方法:

句法

此方法用于写入具有指定开始和结束索引的字符串的一部分。

void write(String s, int off, int len)

此方法用于写入字符数组的一部分。

void write(char[] cbuf, int off, int len)

此方法用于编写单个字符。

void write(int c)

write()方法示例

在本例中,我们将三个参数作为字符串传递给函数,字符串是要写入的源,然后有一个偏移量作为第二个参数,它指示从哪里开始读取字符串的起始点,第三个参数是从哪里开始读取字符串的长度。这里我们有一个字符串“你好,今晚研究”,如果我们从索引 2 中计数 8 个位置,那么它将把文本“llo Stud”写入文件。

import java.io.BufferedWriter;
import java.io.FileWriter;
public class StudyTonight 
{
    public static void main(String args[])
    {
        try
        {
            String str = "Hello Studytonight";
            FileWriter writer = new FileWriter("E:\\studytonight\\output.txt");  
            BufferedWriter buffer = new BufferedWriter(writer);  
            buffer.write(str, 2, 8);  
            buffer.close();  
            System.out.println("Data is written to the file successfully..."); 
        }
        catch(Exception e)
        {
            System.out.print(false);
        }
    }
}

数据成功写入文件...

输出. txt

llo Stud

例 2

这个例子类似于上面给出的例子,但不同的是,这里我们传递了一个字符数组作为源,然后偏移量作为索引,从这里我们将开始读取要写入缓冲区的文本和数据长度。

import java.io.BufferedWriter;
import java.io.FileWriter;
public class StudyTonight 
{
    public static void main(String args[])
    {
        try
        {
            char arr[] = {'H', 'e', 'l', 'l', 'o', 'S', 't', 'u', 'd', 'y', 't', 'o', 'n', 'i', 'g', 'h', 't'};
            FileWriter writer = new FileWriter("E:\\studytonight\\output.txt");  
            BufferedWriter buffer = new BufferedWriter(writer);  
            buffer.write(arr, 2, 8);  
            buffer.close();  
            System.out.println("Data is written to the file successfully..."); 
        }
        catch(Exception e)
        {
            System.out.print(false);
        }
    }
}

数据成功写入文件...

输出. txt

lloStudy

写(整数)方法示例

在本例中,我们将一个整数作为数据源作为该特定字符的 ASCII 码传递,并且该方法将把该 ASCII 码写入 BufferedWriter。这里我们不需要传递长度,因为我们只有一个字符。

import java.io.BufferedWriter;
import java.io.FileWriter;
public class StudyTonight 
{
    public static void main(String args[])
    {
        try
        {
            FileWriter writer = new FileWriter("E:\\studytonight\\output.txt");  
            BufferedWriter buffer = new BufferedWriter(writer);  
            buffer.write(65);  
            buffer.close();  
            System.out.println("Data is written to the file successfully..."); 
        }
        catch(Exception e)
        {
            System.out.print(false);
        }
    }
}

数据成功写入文件...

输出. txt

A

结论

在本教程中,我们学习了 Java 中 BufferedWriter 的 write()方法。这个方法有三种重载方法,void write(char[] cbuf, int off, int len)void write(int c)和void write(String str, int off, int len)方法。