我有一个包含数据的文件。在我的主要方法中,我读入文件并关闭文件。我调用另一种方法,在原始文件的同一文件夹中创建一个新文件。所以现在我有两个文件,原始文件和从我调用的方法生成的文件。我需要另一种方法从原始文件中获取数据并将其写入创建的新文件。我该怎么做?
import java.io.*;
import java.util.Scanner;
import java.util.*;
import java.lang.*;
public class alice {
public static void main(String[] args) throws FileNotFoundException {
String filename = ("/Users/DAndre/Desktop/Alice/wonder1.txt");
File textFile = new File(filename);
Scanner in = new Scanner(textFile);
in.close();
newFile();
}
public static void newFile() {
final Formatter x;
try {
x = new Formatter("/Users/DAndre/Desktop/Alice/new1.text");
System.out.println("you created a new file");
} catch (Exception e) {
System.out.println("Did not work");
}
}
private static void newData() {
}
}
答案 0 :(得分:0)
如果您的要求是将原始文件内容复制到新文件。那么这可能是一个解决方案。
<强>解决方案:强>
首先,使用BufferedReader
读取原始文件,然后将您的内容传递给另一个使用PrintWriter
创建新文件的方法。并将您的内容添加到新文件中。
示例:
public class CopyFile {
public static void main(String[] args) throws FileNotFoundException, IOException {
String fileName = ("C:\\Users\\yubaraj\\Desktop\\wonder1.txt");
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = br.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
line = br.readLine();
}
/**
* Pass original file content as string to another method which
* creates new file with same content.
*/
newFile(stringBuilder.toString());
} finally {
br.close();
}
}
public static void newFile(String fileContent) {
try {
String newFileLocation = "C:\\Users\\yubaraj\\Desktop\\new1.txt";
PrintWriter writer = new PrintWriter(newFileLocation);
writer.write(fileContent);//Writes original file content into new file
writer.close();
System.out.println("File Created");
} catch (Exception e) {
e.printStackTrace();
}
}
}