The write Method in Java

The java.io.FileWriter.write method is overloaded to take either a string, a single character, or an array of characters as an argument. The WriteFile example used a string, text, as an argument to the write method. The second version of WriteFile has the same functionality as before, except that it converts the output string to a char array, charbuff, then uses charbuff as an argument to the write method.


WriteFile

import java.io.*;

public class WriteFile
{

public static void main(String[] args) throws IOException
{
String text;
char charbuff[] = new char [30];
int i;
int j;
FileWriter out = new FileWriter(''File1.txt");
for (i=1; i<11; i++)
{
text = "Line " + i + " of text\n";
for (j=0; j < text.length(); j++)
{
charbuff[j] = text.charAt(j);
}
out.write(charbuff, 0 ,text.length() );
}
out.close();
}



The char array is created in line 8. We have dispensed with creating a file object; instead, in line 12, we supply the file name as an argument to the FileWriter constructor.

In lines 15–17, we have a for loop that takes each character in a string, converts it to a type char, and assigns it to the charbuff array. The method java.langString.charAt(j) takes the jth character of the supplied string and returns a char value.

In line 18, we use the write(char Array, offset, length) form of the write method to output charbuff to the output stream, out.

No comments:

Post a Comment