try {//create a file named "testfile.txt" in the current working directoryFile myFile = new File("testfile.txt");if ( myFile.createNewFile() ) {System.out.println("Success!");} else {System.out.println("Failure!");}} catch ( IOException ioe ) { ioe.printStackTrace(); }
import java.io.BufferedWriter;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;import java.io.Writer;
public class writer {public void writing() {try {//Whatever the file path is.File statText = new File("E:/Java/Reference/bin/images/statsTest.txt");FileOutputStream is = new FileOutputStream(statText);OutputStreamWriter osw = new OutputStreamWriter(is);Writer w = new BufferedWriter(osw);w.write("POTATO!!!");w.close();} catch (IOException e) {System.err.println("Problem writing to the file statsTest.txt");}}
public static void main(String[]args) {writer write = new writer();write.writing();}}
String content = "This is the content to write into a file";File file = new File("filename.txt");FileWriter fw = new FileWriter(file.getAbsoluteFile());BufferedWriter bw = new BufferedWriter(fw);bw.write(content);bw.close(); // Be sure to close BufferedWriter
System.out.println("Choose folder to create file");JFileChooser c = new JFileChooser();c.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);c.showOpenDialog(c);c.getSelectedFile();f = c.getSelectedFile(); // File f - global variableString newfile = f + "\\hi.doc";//.txt or .doc or .htmlFile file = new File(newfile);
try {//System.out.println(f);boolean flag = file.createNewFile();
if(flag == true) {JOptionPane.showMessageDialog(rootPane, "File created successfully");}else {JOptionPane.showMessageDialog(rootPane, "File already exists");}/* Or use exists() function as follows:if(file.exists() == true) {JOptionPane.showMessageDialog(rootPane, "File already exists");}else {JOptionPane.showMessageDialog(rootPane, "File created successfully");}*/}catch(Exception e) {// Any exception handling method of your choice}
JFileChooser c = new JFileChooser();c.showOpenDialog(c);File writeFile = c.getSelectedFile();String content = "Input the data here to be written to your file";
try {FileWriter fw = new FileWriter(writeFile);BufferedWriter bw = new BufferedWriter(fw);bw.append(content);bw.append("hiiiii");bw.close();fw.close();}catch (Exception exc) {System.out.println(exc);}
import java.io.File;import java.io.FileWriter;import java.io.IOException;
public class FileWriterExample {public static void main(String [] args) {FileWriter fw= null;File file =null;try {file=new File("WriteFile.txt");if(!file.exists()) {file.createNewFile();}fw = new FileWriter(file);fw.write("This is an string written to a file");fw.flush();fw.close();System.out.println("File written Succesfully");} catch (IOException e) {e.printStackTrace();}}}
FileWriter fr = new FileWriter("your_file_name.txt"); // After '.' write// your file extention (".txt" in this case)fr.write("Things you want to write into the file"); // Warning: this will REPLACE your old file content!fr.close();
package fileoperations;import java.io.File;import java.io.IOException;
public class SimpleFile {public static void main(String[] args) throws IOException {File file =new File("text.txt");file.createNewFile();System.out.println("File is created");FileWriter writer = new FileWriter(file);
// Writes the content to the filewriter.write("Enter the text that you want to write");writer.flush();writer.close();System.out.println("Data is entered into file");}}
//Reading from the file the first line which contains word "confidential"try {Stream<String> lines = Files.lines(FILE_PATH);Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();if(containsJava.isPresent()){System.out.println(containsJava.get());}} catch (IOException e) {e.printStackTrace();}
import java.io.BufferedWriter;import java.io.File;import java.io.FileWriter;
public class CreateFiles {
public static void main(String[] args) {try{// Create new fileString content = "This is the content to write into create file";String path="D:\\a\\hi.txt";File file = new File(path);
// If file doesn't exists, then create itif (!file.exists()) {file.createNewFile();}
FileWriter fw = new FileWriter(file.getAbsoluteFile());BufferedWriter bw = new BufferedWriter(fw);
// Write in filebw.write(content);
// Close connectionbw.close();}catch(Exception e){System.out.println(e);}}}
try {File fout = new File("myOutFile.txt");FileOutputStream fos = new FileOutputStream(fout);BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));bw.write("Write somthing to the file ...");bw.newLine();bw.close();} catch (FileNotFoundException e){// File was not founde.printStackTrace();} catch (IOException e) {// Problem when writing to the filee.printStackTrace();}
使用FileWriter
try {FileWriter fw = new FileWriter("myOutFile.txt");fw.write("Example of content");fw.close();} catch (FileNotFoundException e) {// File not founde.printStackTrace();} catch (IOException e) {// Error when writing to the filee.printStackTrace();}
使用PrintWriter
try {PrintWriter pw = new PrintWriter("myOutFile.txt");pw.write("Example of content");pw.close();} catch (FileNotFoundException e) {// File not founde.printStackTrace();} catch (IOException e) {// Error when writing to the filee.printStackTrace();}
使用OutputStreamWriter
try {File fout = new File("myOutFile.txt");FileOutputStream fos = new FileOutputStream(fout);OutputStreamWriter osw = new OutputStreamWriter(fos);osw.write("Soe content ...");osw.close();} catch (FileNotFoundException e) {// File not founde.printStackTrace();} catch (IOException e) {// Error when writing to the filee.printStackTrace();}
public void saveDataInFile(String data) throws IOException {FileOutputStream outputStream = new FileOutputStream(fileName);byte[] strToBytes = data.getBytes();outputStream.write(strToBytes);
outputStream.close();}
使用PrintWriter编写我们可以使用PrintWriter将格式化文本写入文件:
public void saveDataInFile() throws IOException {FileWriter fileWriter = new FileWriter(fileName);PrintWriter printWriter = new PrintWriter(fileWriter);printWriter.print("Some String");printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);printWriter.close();}
使用BufferedWriter写作:使用BufferedWriter将字符串写入新文件:
public void saveDataInFile(String data) throws IOException {BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));writer.write(data);
writer.close();}
将字符串附加到现有文件:
public void saveDataInFile(String data) throws IOException {BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));writer.append(' ');writer.append(data);
writer.close();}
┌───────────────────────────┬────────────────────────┬─────────────┬──────────────┐│ │ Buffer for │ Can specify │ Throws ││ │ large files? │ encoding? │ IOException? │├───────────────────────────┼────────────────────────┼─────────────┼──────────────┤│ OutputStreamWriter │ Wrap in BufferedWriter │ Y │ Y ││ FileWriter │ Wrap in BufferedWriter │ │ Y ││ PrintWriter │ Y │ Y │ ││ Files.write() │ │ Y │ Y ││ Files.newBufferedWriter() │ Y │ Y │ Y │└───────────────────────────┴────────────────────────┴─────────────┴──────────────┘