有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从一个文本文件中获取数据并将其移动到新的文本文件

我有一个里面有数据的文件。在我的main方法中,我读入文件并关闭文件。我调用了另一个方法,该方法在原始文件的同一文件夹中创建了一个新文件。现在我有两个文件,原始文件和我调用的方法生成的文件。我需要另一种方法,从原始文件中获取数据并将其写入创建的新文件。我该怎么做

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() {
    }

}

共 (1) 个答案

  1. # 1 楼答案

    如果您的要求是将原始文件内容复制到新文件。那么这可能是一个解决方案

    解决方案:

    首先,使用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();
        }
      }
    }