首先,我们需要创建一个Java类,例如WriteStringToFile.java,然后编写以下代码: importjava.io.BufferedWriter;importjava.io.FileWriter;importjava.io.IOException;publicclassWriteStringToFile{publicstaticvoidmain(String[]args){Stringcontent="Hello, this is the content to be written to the file.";try(BufferedWri...
importjava.io.FileWriter;importjava.io.IOException;publicclassFileWriterExample{publicstaticvoidmain(String[]args){Stringcontent="Hello, World!";try{FileWriterwriter=newFileWriter("output.txt");writer.write(content);writer.close();System.out.println("Successfully wrote to the file.");}catch(IOException...
publicstaticvoidlx1()throwsIOException {//将字符串直接写到文件中FileUtils.writeStringToFile(newFile("D:\\ja.txt"),"春天来哦了"); } }
public void WriteStringToFile(String filePath) { try { File file = new File(filePath); PrintStream ps = new PrintStream(new FileOutputStream(file)); ps.println("http://www.jb51.net");// 往文件里写入字符串 ps.append("http://www.jb51.net");// 在已有的基础上添加字符串 } catch (Fi...
public class WriteStringToFile { public static void main(String[] args) { try { String aString = "Hello你好"; FileWriter fw = new FileWriter("c:/out.fw.txt"); fw.write(aString); fw.close(); //默认gbk编码9字节 /// OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(...
import java.io.ByteArrayInputStream;import java.io.OutputStream;publicclassStringToFile{publicstaticvoidconvertToFileStream(String content, OutputStream outputStream)throws Exception { ByteArrayInputStream inputStream = new ByteArrayInputStream(content.getBytes());byte[] buffer = newbyte[1024];int le...
java: write file importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;String directory="e:/test";String filename="f.txt";File file=newFile(directory);if(!file.exists()){file.mkdirs();}File file2=newFile(directory,filename);if(!file2.exists()){try{file2....
public void PrintStreamDemo() { try { FileOutputStream out = new FileOutputStream("D:/test.txt");PrintStream p = new PrintStream(out);p.println("I'm the text to be write");} catch (FileNotFoundException e) { e.printStackTrace();} } 2. 使用StringBuffer写文件:public void...
完整的参考代码如下 import java.io.FileOutputStream;//导入包public class Demo {public static void main(String[] args) throws Exception {//抛出异常FileOutputStream fos = new FileOutputStream("E:\\1_int.txt");//路径需要双引号括起来fos.write(String.valueOf(65).getBytes());// 把...
调用BufferedWriter的write()方法写入数据。 调用BufferedWriter的newline()方法写入换行符。 关闭BufferedWriter和FileWriter。 示例代码如下: import java.io.BufferedWriter;import java.io.FileWriter;import java.io.IOException;publicclassFileWritingExample{publicstaticvoidmain(String[]args){StringfilePath="path/to/you...