📜  将字符串保存到文件的Java程序

📅  最后修改于: 2022-05-13 01:54:22.699000             🧑  作者: Mango

将字符串保存到文件的Java程序

桌面上有一个名为“gfg.txt”的演示文件,作为机器上的本地目录作为参考。在编写程序之前创建一个空文件,并将该文件的特定路径提供给程序。

方法:

  1. 使用 Files 类的writeString() 方法
  2. 使用 Files 类的write() 方法
  3. 使用 Filewriter 类的 writer() 方法
  4. 使用 Bufferedwriter 类的 write() 方法
  5. 使用 PrintWriter 类的 write() 方法

让我们通过干净的Java程序实现相同的方法来单独讨论每种方法,以对处理它们有一个公平的想法。

方法一:使用Files类的writeString()方法

Java中 File 类的writeString()方法用于将内容写入指定文件。 ' Java.nio.file.Files'类有一个预定义的writeString() 方法,该方法用于使用 UTF-8 字符集将所有内容写入文件。



句法:

Files.writeString(path, string, options)

参数:

  • Path:数据类型为Path的文件路径
  • 字符串:将在文件中输入的指定字符串 返回类型字符串。
  • 选项:在文件中输入字符串的不同选项。就像将字符串附加到文件中,用当前字符串覆盖文件中的所有内容等

返回值:此方法不返回任何值。

程序:

  • 创建文件的一个实例。
  • 使用实例、字符串和字符集调用 Files.writeString() 方法。

例子

Java
// Java Program to Save a String to a File
// Using Files.writeString() method
 
// Importing required classes
import java.io.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
 
// Main class
public class GFG {
   
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an instance of file
        Path path
            = Paths.get("C:\\Users\\HP\\Desktop\\gfg.txt");
 
        // Custom string as an input
        String str
            = "Geeks for Geeks \nWelcome to computer science portal \nHello Geek";
 
        // Try block to check for exceptions
        try {
            // Now calling Files.writeString() method
            // with path , content & standard charsets
            Files.writeString(path, str,
                              StandardCharsets.UTF_8);
        }
 
        // Catch block to handle the exception
        catch (IOException ex) {
            // Print messqage exception occured as
            // invalid. directory local path is passed
            System.out.print("Invalid Path");
        }
    }
}


Java
// Java Program to Save a String to a File
// Using Files.write() method
 
// Importing required classes
import java.io.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
 
// Main class
public class GFG {
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an instance of file
        Path path
            = Paths.get("C:\\Users\\HP\\Desktop\\gfg.txt");
 
        // Custom string as an input
        String str
            = "Geeks for Geeks \nWelcome to computer science portal \nHello Geek!";
 
        // Converting string to byte array
        // using getBytes() method
        byte[] arr = str.getBytes();
 
        // Try block to check for exceptions
        try {
            // Now calling Files.write() method using path
            // and byte array
            Files.write(path, arr);
        }
 
        // Catch block to handle the exceptions
        catch (IOException ex) {
            // Print message as exception occured when
            // invalid path of local machine is passed
            System.out.print("Invalid Path");
        }
    }
}


Java
// Java Program to Save a String to a File
// Using FileWriter class
 
// Importing required classes
import java.io.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
 
public class GFG
{
    public static void main(String[] args) throws IOException
    {
        //creating the instance of file
        File path = new File("C:\\Users\\HP\\Desktop\\gfg.txt");
       
      //passing file instance in filewriter
        FileWriter wr = new FileWriter(path);
 
        //calling writer.write() method with the string
        wr.write("Geeks for Geeks \nWelcome to computer science portal \nHello Geek!!");
         
        //flushing the writer
        wr.flush();
         
        //closing the writer
        wr.close();
    }
}


Java
// Java Program to Save a String to a File
// Using BufferedWriter class
 
// Importing required classes
import java.io.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
 
// MAin class
public class GFG {
   
    // Main driver method
    public static void main(String[] args)
        throws IOException
    {
        // Creating an instance of file
        File path
            = new File("C:\\Users\\HP\\Desktop\\gfg.txt");
 
        // Declaring a bufferedwriter with filewriter
        BufferedWriter writer
            = new BufferedWriter(new FileWriter(path));
 
        // Try block to check for exceptions
        try (writer) {
            // Calling writer.write() method with string
            writer.write(
                "Geeks for Geeks \nWelcome to computer science portal \nHello Geek!!!");
        }
 
        // Catch block to handle the exceptions
        catch (IOException e) {
            // Print message as exception occured
            // when invalid path from local machine is
            // passed
            System.out.print("Invalid Path");
        }
    }
}


Java
// Java Program to Save a String to a File
// Using PrintWriter class
 
// Importing required classes
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
 
// Main clas
public class GFG {
   
    // Main driver method
    public static void main(String[] args)
        throws FileNotFoundException
    {
        // Creating an instance of file
        File path
            = new File("C:\\Users\\HP\\Desktop\\gfg.txt");
 
        // Declaring the print writer with path
        PrintWriter pw = new PrintWriter(path);
 
        // Now calling writer() method with string
        pw.write(
            "Geeks for Geeks \nWelcome to computer science portal \nHello Geek!!!!");
 
        // Flushing the print writer
        pw.flush();
 
        // Lastly closing the printwriter
        // using the close() method
        pw.close();
    }
}




输出:

Geeks for Geeks
Welcome to computer science portal
Hello Geek

方法二:使用Files类的write()方法

Java .nio.file.Files 类有一个预定义的 write() 方法,用于将指定的文本写入文件。

程序:

  1. 创建文件的实例。
  2. 使用字符串 .getBytes() 方法将字符串转换为字节数组。
  3. 最后使用文件实例和字节数组调用方法,即 Files.write()。

例子

Java

// Java Program to Save a String to a File
// Using Files.write() method
 
// Importing required classes
import java.io.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
 
// Main class
public class GFG {
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an instance of file
        Path path
            = Paths.get("C:\\Users\\HP\\Desktop\\gfg.txt");
 
        // Custom string as an input
        String str
            = "Geeks for Geeks \nWelcome to computer science portal \nHello Geek!";
 
        // Converting string to byte array
        // using getBytes() method
        byte[] arr = str.getBytes();
 
        // Try block to check for exceptions
        try {
            // Now calling Files.write() method using path
            // and byte array
            Files.write(path, arr);
        }
 
        // Catch block to handle the exceptions
        catch (IOException ex) {
            // Print message as exception occured when
            // invalid path of local machine is passed
            System.out.print("Invalid Path");
        }
    }
}

输出:

Geeks for Geeks
Welcome to computer science portal
Hello Geek!

方法三:使用 FileWriter 类的 writer() 方法



Filewriter 类用于在文件上写入一些数据。这是一种将数据写入文件的简单方法。

程序:

  • 创建文件的一个实例。
  • 将文件实例传递给 filewriter。
  • 现在通过带有字符串数据的文件编写器调用writer() 方法
  • 刷新文件资源。
  • 关闭文件资源。

例子

Java

// Java Program to Save a String to a File
// Using FileWriter class
 
// Importing required classes
import java.io.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
 
public class GFG
{
    public static void main(String[] args) throws IOException
    {
        //creating the instance of file
        File path = new File("C:\\Users\\HP\\Desktop\\gfg.txt");
       
      //passing file instance in filewriter
        FileWriter wr = new FileWriter(path);
 
        //calling writer.write() method with the string
        wr.write("Geeks for Geeks \nWelcome to computer science portal \nHello Geek!!");
         
        //flushing the writer
        wr.flush();
         
        //closing the writer
        wr.close();
    }
}

输出:

Geeks for Geeks
Welcome to computer science portal
Hello Geek!!

方法四:使用BufferedWriter类的write()方法

BufferedWriter 类基本上提供了一个用于写入实例的缓冲区。我们可以将 PrintWriter 和 FileWriter 等其他一些编写器包装到 BufferedWriter 中。 BufferedWriter 对于对文件进行多次写入操作和写入多个文件非常有效。 BufferedWriter 比 Filewriter 效率更高。

程序:

  1. 创建文件的一个实例。
  2. 使用文件编写器声明流。
  3. 使用字符串数据在流上调用 write() 方法。

例子

Java

// Java Program to Save a String to a File
// Using BufferedWriter class
 
// Importing required classes
import java.io.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
 
// MAin class
public class GFG {
   
    // Main driver method
    public static void main(String[] args)
        throws IOException
    {
        // Creating an instance of file
        File path
            = new File("C:\\Users\\HP\\Desktop\\gfg.txt");
 
        // Declaring a bufferedwriter with filewriter
        BufferedWriter writer
            = new BufferedWriter(new FileWriter(path));
 
        // Try block to check for exceptions
        try (writer) {
            // Calling writer.write() method with string
            writer.write(
                "Geeks for Geeks \nWelcome to computer science portal \nHello Geek!!!");
        }
 
        // Catch block to handle the exceptions
        catch (IOException e) {
            // Print message as exception occured
            // when invalid path from local machine is
            // passed
            System.out.print("Invalid Path");
        }
    }
}

输出:

Geeks for Geeks
Welcome to computer science portal
Hello Geek!!!

方法五:使用PrintWriter类的write()方法

PrintWriter 类是 writer 类的扩展。 PrintWriter 类用于使用 write() 方法将字符串数据写入文件。

程序:

  1. 创建文件的一个实例。
  2. 创建一个 PrintWriter 流并将文件实例传递给它。
  3. 使用数据调用 write 方法。
  4. 冲洗流。
  5. 关闭流。

例子



Java

// Java Program to Save a String to a File
// Using PrintWriter class
 
// Importing required classes
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
 
// Main clas
public class GFG {
   
    // Main driver method
    public static void main(String[] args)
        throws FileNotFoundException
    {
        // Creating an instance of file
        File path
            = new File("C:\\Users\\HP\\Desktop\\gfg.txt");
 
        // Declaring the print writer with path
        PrintWriter pw = new PrintWriter(path);
 
        // Now calling writer() method with string
        pw.write(
            "Geeks for Geeks \nWelcome to computer science portal \nHello Geek!!!!");
 
        // Flushing the print writer
        pw.flush();
 
        // Lastly closing the printwriter
        // using the close() method
        pw.close();
    }
}

输出:

Geeks for Geeks
Welcome to computer science portal
Hello Geek!!!!