用Java创建和写入(文本)文件的最简单方法是什么?
当前回答
public static void writefromFile(ArrayList<String> lines, String destPath) {
FileWriter fw;
try {
fw = new FileWriter(destPath);
for (String str : lines) {
fw.write(str);
}
fw.close();
} catch (IOException ex) {
JOptionPane.showMessageDialog("ERROR: exception was: " + ex.toString());
}
File f = new File(destPath);
f.setExecutable(true);
}
其他回答
使用输入和输出流读取和写入文件:
//Coded By Anurag Goel
//Reading And Writing Files
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class WriteAFile {
public static void main(String args[]) {
try {
byte array [] = {'1','a','2','b','5'};
OutputStream os = new FileOutputStream("test.txt");
for(int x=0; x < array.length ; x++) {
os.write( array[x] ); // Writes the bytes
}
os.close();
InputStream is = new FileInputStream("test.txt");
int size = is.available();
for(int i=0; i< size; i++) {
System.out.print((char)is.read() + " ");
}
is.close();
} catch(IOException e) {
System.out.print("Exception");
}
}
}
public class Program {
public static void main(String[] args) {
String text = "Hello world";
BufferedWriter output = null;
try {
File file = new File("example.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
} catch ( IOException e ) {
e.printStackTrace();
} finally {
if ( output != null ) {
try {
output.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
}
用Java创建和写入文件的一种非常简单的方法:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class CreateFiles {
public static void main(String[] args) {
try{
// Create new file
String 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 it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
// Write in file
bw.write(content);
// Close connection
bw.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
创建示例文件:
try {
File file = new File ("c:/new-file.txt");
if(file.createNewFile()) {
System.out.println("Successful created!");
}
else {
System.out.println("Failed to create!");
}
}
catch (IOException e) {
e.printStackTrace();
}
我能找到的最简单的方法是:
Path sampleOutputPath = Paths.get("/tmp/testfile")
try (BufferedWriter writer = Files.newBufferedWriter(sampleOutputPath)) {
writer.write("Hello, world!");
}
它可能只适用于1.7+。
推荐文章
- javax.transaction.Transactional vs . org.springframework.transaction.annotation.Transactional
- Java 8接口方法中不允许“同步”的原因是什么?
- 如何找到Java堆大小和内存使用(Linux)?
- 使用Enum实现单例(Java)
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 如何在Java中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠
- 在方法参数中使用NotNull注释
- Spring MVC中处理可选参数的@RequestParam
- Tomcat:如何查找正在运行的Tomcat版本?
- 如何在Python中连接文本文件?
- “java”、“javaw”和“javaws”之间有什么区别?
- 将Date对象转换为日历对象