java如何将文件另存为
时间: 2024-03-19 13:44:16 浏览: 27
你可以使用 Java 中的 File 类和 FileWriter 类来实现将文件另存为的功能。以下是一个简单的示例代码:
```java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileSaveAsExample {
public static void main(String[] args) {
String content = "This is the content to write into the file";
try {
File file = new File("example.txt");
FileWriter writer = new FileWriter(file);
writer.write(content);
writer.close();
System.out.println("File saved as: " + file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上述代码中,我们首先定义了要写入文件的内容,然后创建了一个 File 对象来表示文件。接下来,我们使用 FileWriter 类来创建一个写入器,并将内容写入文件中。最后,我们关闭写入器并输出文件的绝对路径。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)