如何在Java中写入File [英] How do I write to File in Java
本文介绍了如何在Java中写入File的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法将内容写入java中的文件。请帮助:
I am not able to write the contents to the file in java. Please help:
//Reads an input file containing numbers or strings and sorts them and writes to a new file
import java.io.*;
import java.util.*;
public class FileSort
{
private Scanner input;
private Formatter output;
private List<Integer> list;
private void openFile(String fileName)
{
try{
input = new Scanner(new File(fileName));
}
catch(FileNotFoundException fileNotFoundException)
{
System.err.println("Error opening the file. File Not Found");
System.exit(1);
}
}
private void readFile(String fileName)
{
try{
list = new ArrayList<Integer>();
while(input.hasNext())
{
list.add(Integer.valueOf(input.next()));
}
Collections.sort(list);
//System.out.printf("\nThe list is: %s",list);
}
catch(NoSuchElementException elementException)
{
System.err.println("File improperly formatted.");
input.close();
System.exit(1);
}
}
private void writeFile(String fileName)
{
try{
output = new Formatter(fileName);
output.format("%s", "Hello");
}
catch(Exception e)
{
System.err.println(e.getMessage());
output.close();
System.exit(1);
}
}
public static void main(String[] args)
{
FileSort fs = new FileSort();
fs.openFile("input.txt");
fs.readFile("input.txt");
fs.writeFile("output.txt");
}
}
推荐答案
参考:
1. 读取,编写和创建文件 [ ^ ]
2. how-to-write-to-file-in-java-bufferedwriter-example [ ^ ]
Refer:
1. Reading, Writing, and Creating Files[^]
2. how-to-write-to-file-in-java-bufferedwriter-example[^]
你没有在writefile中尝试任何文件操作
You are not attempting any file operations in writefile
try{
output = new Formatter(fileName);
output.format("%s", "Hello");
}
您正在格式化字符串文件名,然后用新字符串覆盖该格式。没有文件操作。
读过这个
http://www.homeandlearn.co.uk/java/write_to_textfile.html [ ^ ]
希望它有所帮助。 />
/ Darren
You are formatting the string filename, then overwriting that format with a new string. No file operations.
Have a read of this
http://www.homeandlearn.co.uk/java/write_to_textfile.html[^]
Hope it helps.
/Darren
您需要使用FileReader和FileWriter。例如:
You need to use FileReader and FileWriter. For example:
try {
FileWriter writer = new FileWriter("output.txt");
writer.write("hello");
writer.flush();
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
这篇关于如何在Java中写入File的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文