首页 > 解决方案 > java - 如何在一行中在java中的一行中将内容从一个文件复制到另一个文件

问题描述

所以我的代码所做的是检查文件是否有一定数量的列。如果列小于指定的列数,则从下一行添加字符串“null”。此外,代码使用 org.apache.io 复制文件“text”中的内容并将其放入名为“test”的新文件中。(文件“文本分两行”中的内容)。我希望内容在单行中显示在文件“test”中。

    package MySQL;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import org.apache.commons.io.*;

public class Add {
    public static void main(String args[]) throws IOException {
        File file = new File("C:\\Users\\dhruv\\Desktop\\Practicals\\IntelliJ\\src\\MySQL\\text.txt");
        Scanner scanner = null;

        try {
            scanner = new Scanner(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        int number = 0;
        if (scanner.hasNextLine()) {
            number = scanner.nextLine().split(" ").length;
        }
        System.out.println(number);

        scanner.close();

        if (number < 10) {

            FileWriter bw_1 = new FileWriter("C:\\Users\\dhruv\\Desktop\\Practicals\\IntelliJ\\src\\MySQL\\text.txt", true);
            BufferedWriter bw = new BufferedWriter(bw_1);
            PrintWriter out = new PrintWriter(bw);
            for (int i = 0; i < 10-number; i++)
            {
                out.write("Null");
                out.write(" ");

            }
            out.close();
        }
        File file_1 = new File("C:\\Users\\dhruv\\Desktop\\Practicals\\IntelliJ\\src\\MySQL\\text.txt");

        String content = null;
        try {
            content = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(content);

        Path path = Paths.get("C:\\Users\\dhruv\\Desktop\\Practicals\\IntelliJ\\src\\MySQL\\test.txt");
        //String contents = ;

        try {
            Files.writeString(path, content, StandardCharsets.UTF_8);
        } catch (IOException ex) {

        }



    }
}

“文本文件

标签: java

解决方案


推荐阅读