简体   繁体   English

读写txt文件

[英]reading and writing txt files

I am working on a java program where:我正在开发一个 Java 程序,其中:

program reads in two txt files(txt1 & txt2) it then prints out the txt1 and txt2 to txt3 alternating "lines" from each txt1 and txt2.程序读入两个 txt 文件(txt1 和 txt2),然后将 txt1 和 txt2 打印到 txt3,从每个 txt1 和 txt2 交替“行”。

example: txt1 =示例:txt1 =

this is first is one这是第一个

txt2= that was two txt2= 那是两个

txt3 should be: this is first that is was one two txt3 应该是:这是第一,是一二

I am not sure what I am missing...any help would be appreciated.我不确定我错过了什么......任何帮助将不胜感激。

code:代码:

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);
}}

I am working on a java program where:我正在使用以下Java程序:

program reads in two txt files(txt1 & txt2) it then prints out the txt1 and txt2 to txt3 alternating "lines" from each txt1 and txt2.程序读取两个txt文件(txt1和txt2),然后从每个txt1和txt2交替输出“行”,将txt1和txt2打印到txt3。

example: txt1 =例如:txt1 =

this is first is one这是第一是一个

txt2= that was two txt2 =那是两个

txt3 should be: this is first that is was one two txt3应该是:这是第一个,是两个

I am not sure what I am missing...any help would be appreciated.我不确定我缺少什么...任何帮助将不胜感激。

code:代码:

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);
}}

Use List<String> and java.nio like this:像这样使用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();
    }
}

This approach still uses most of your original code.这种方法仍然使用您的大部分原始代码。

The idea is to keep separate lists of lines for each file, and then loop over the total amount of lines, switching to a different list on each iteration.这个想法是为每个文件保留单独的行列表,然后遍历总行数,在每次迭代时切换到不同的列表。

If the files have a different amount of lines in them, you will need to add some logic (otherwise you will get an IndexOutOfBounds error when accessing a line number that does not exist)如果文件中的行数不同,则需要添加一些逻辑(否则在访问不存在的行号时会出现 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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM