чтение и запись текстовых файлов - PullRequest
0 голосов
/ 01 декабря 2019

Я работаю над Java-программой, в которой:

программа считывает в два txt-файла (txt1 & txt2), а затем печатает чередующиеся «строки» из txt1 и txt2 в txt3 из каждого txt1 и txt2.

пример: txt1 =

это первый - один

txt2 = это два

txt3 должно быть: это первый, то есть один два

Я не уверен, что мне не хватает ... любая помощь будет оценена.

код:

package combine;

import java.io.*;
import java.util.*;
import java.nio.file.*;

public class Main{

public static void main(String[] args) throws IOException{
   String targetDir = "C:\\Parts";
   String outputFile = "C:\\Parts\\complete\\TheRavensGreenEggs.txt";

   File dir = new File(targetDir);
   File[] files = dir.listFiles(new FilenameFilter() {
     // Only import "txt" files
     @Override
     public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".txt");
    }
});

// Reads all "txt" file lines into a List
List<String> inputFileLines = new ArrayList<>();{
for (File file : files) {
    inputFileLines.addAll(Files.readAllLines(Paths.get(file.getAbsolutePath())));
}}


// Writes the List to the console
for (String line : inputFileLines) {
    System.out.println(line);
}

// Writes the List to a single "TheRavensGreenEggs.txt" file
Files.write(Paths.get(outputFile), inputFileLines, StandardOpenOption.CREATE);
}}

Ответы [ 3 ]

0 голосов
/ 01 декабря 2019

Вы можете сделать это следующим образом:

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) throws IOException {
        String targetDir = "/Users/arvind.avinash/testfiles";
        String outputFile = "/Users/arvind.avinash/testfiles/TheRavensGreenEggs.txt";

        File dir = new File(targetDir);
        File[] files = dir.listFiles(new FilenameFilter() {
            // Only import "txt" files
            @Override
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".txt");
            }
        });

        // Reads all "txt" file lines into a List
        List<String> inputFileLines = new ArrayList<String>();

        for (File file : files) {
            inputFileLines.addAll(Files.readAllLines(Paths.get(file.getAbsolutePath())));
        }

        // Create String arrays by splitting the content at " "
        // inputFileLines.get(0) has the content from first file and
        // inputFileLines.get(1) has content from the second file
        String fromFirstFile[] = inputFileLines.get(0).split(" ");
        String fromSecondFile[] = inputFileLines.get(1).split(" ");

        // Merge the content from the two String arrays by adding them alternatively
        StringBuilder sb = new StringBuilder();
        int i;
        for (i = 0; i < fromFirstFile.length && i < fromSecondFile.length; i++) {
            sb.append(fromFirstFile[i]);
            sb.append(" ");
            sb.append(fromSecondFile[i]);
            sb.append(" ");
        }

        // Append the remaining content from the longer file to the merged content
        boolean isFirstBigger = fromFirstFile.length > fromSecondFile.length ? true : false;
        int j;
        if (isFirstBigger) {
            for (j = i; j < fromFirstFile.length; j++) {
                sb.append(fromFirstFile[j]);
                sb.append(" ");
            }
        } else {
            for (j = i; j < fromSecondFile.length; j++) {
                sb.append(fromSecondFile[j]);
                sb.append(" ");
            }
        }

        // Add the merged content to the target list
        List<String> outFileLines = new ArrayList<String>();
        outFileLines.add(sb.toString().trim());

        // Writes the List to a single "TheRavensGreenEggs.txt" file
        Files.write(Paths.get(outputFile), outFileLines, StandardOpenOption.CREATE);
    }
}
0 голосов
/ 01 декабря 2019

Используйте List<String> и java.nio вот так:

public static void main(String[] args) {
    // define the input paths and the output path
    Path file01Path = Paths.get("Y:\\our\\path\\to\\file_01.txt");
    Path file02Path = Paths.get("Y:\\our\\path\\to\\file_02.txt");
    Path outputPath = Paths.get("Y:\\our\\path\\to\\result.txt");
    // provide a list for the alternating lines
    List<String> resultLines = new ArrayList<>();

    try {
        // read the lines of both files and get them as lists of Strings
        List<String> linesOfFile01 = Files.readAllLines(file01Path);
        List<String> linesOfFile02 = Files.readAllLines(file02Path);
        // find a common border for the iteration: the size of the bigger list
        int maxSize = (linesOfFile01.size() >= linesOfFile02.size())
                ? linesOfFile01.size() : linesOfFile02.size();

        // then loop and store the lines (if there are any) in a certain order
        for (int i = 0; i < maxSize; i++) {
            // lines of file 01 first
            if (i < linesOfFile01.size()) {
                resultLines.add(linesOfFile01.get(i));
            }
            // lines of file 02 second
            if (i < linesOfFile02.size()) {
                resultLines.add(linesOfFile02.get(i));
            }
        }

        // after all, write the content to the result path
        Files.write(outputPath,
                resultLines,
                Charset.defaultCharset(),
                StandardOpenOption.CREATE_NEW);
    } catch (IOException e) {
        System.err.println("Some files system operation failed:");
        e.printStackTrace();
    }
}
0 голосов
/ 01 декабря 2019

Этот подход все еще использует большую часть вашего исходного кода.

Идея состоит в том, чтобы хранить отдельные списки строк для каждого файла, а затем перебирать общее количество строк, переключаясь на другой список на каждой итерации.

Если файлы имеют разныеколичество строк в них, вам нужно будет добавить некоторую логику (в противном случае вы получите ошибку IndexOutOfBounds при доступе к номеру строки, которая не существует)

package combine;

import java.io.*;
import java.util.*;
import java.nio.file.*;

public class Main{

   public static void main(String[] args) throws IOException{

       String targetDir = "C:\\Parts";
       String outputFile = "C:\\Parts\\complete\\TheRavensGreenEggs.txt";

       File dir = new File(targetDir);
       File[] files = dir.listFiles(new FilenameFilter() {
           // Only import "txt" files
           @Override
           public boolean accept(File dir, String name) {
               return name.toLowerCase().endsWith(".txt");
           }
       });

       // Reads all "txt" file lines into a List
       List<List<String>> inputFileLines = new ArrayList<>();{
       for (File file : files){ 
       inputFileLines.add(Files.readAllLines(Paths.get(file.getAbsolutePath()))) 
       }


       // Writes the List to the console
       int n = inputFileLines.size();  // number of files
       int m = inputFileLines.get(0).size() * n; // number of lines in total
       for (int i=0;i<m;i++) {
       System.out.println(inputFileLines.get(i % n).get(i / n));
       }

       // Writes the List to a single "TheRavensGreenEggs.txt" file
       // should be the same as printing to console
    }
}
...