目录
应用案例:使用FileWriter 将"风雨之后,定见彩虹"写入到note.txt文件中
第三种方式:write(char[],off,len):写入指定数组的指定部分
第五种方式:write(string,off,len):写入字符串的指定部分
FileWriter(文件字符输出流)
应用案例:使用FileWriter 将"风雨之后,定见彩虹"写入到note.txt文件中
第一种方式:write(int) -> 写入单个字符
所有的字符本质上还是数字,char 类型 和 int 类型之间可以互用
public class FileWriter01 {
public static void main(String[] args) {
}
@Test
public void FileWrite01(){
String filePath = "D:\\note.txt";
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(filePath);
fileWriter.write('风');
fileWriter.write('雨');
fileWriter.write('之');
fileWriter.write('后');
fileWriter.write(',');
fileWriter.write('定');
fileWriter.write('见');
fileWriter.write('彩');
fileWriter.write('虹');
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("程序结束");
}
}
第二种方式:write(char[]):写入指定数组
public class FileWriter01 {
public static void main(String[] args) {
}
@Test
public void FileWrite02(){
String filePath = "D:\\note.txt";
FileWriter fileWriter = null;
char[] chars = {'风','雨','之','后',',','定','见','彩','虹'};
try {
fileWriter = new FileWriter(filePath);
fileWriter.write(chars);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("程序结束");
}
}
第三种方式:write(char[],off,len):写入指定数组的指定部分
public class FileWriter01 {
public static void main(String[] args) {
}
@Test
public void FileWrite03(){
String filePath = "D:\\note.txt";
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(filePath);
fileWriter.write("风雨之后,定见彩虹".toCharArray(),0,9);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("程序结束");
}
}
第四种方式:write(string):写入整个字符串
public class FileWriter01 {
public static void main(String[] args) {
}
@Test
public void FileWrite04(){
String filePath = "D:\\note.txt";
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(filePath);
fileWriter.write("风雨之后,定见彩虹");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("程序结束");
}
}
第五种方式:write(string,off,len):写入字符串的指定部分
public class FileWriter01 {
public static void main(String[] args) {
}
@Test
public void FileWrite05(){
String filePath = "D:\\note.txt";
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(filePath);
fileWriter.write("风雨之后,定见彩虹",0,9);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("程序结束");
}
}