简体   繁体   English

如何在Java中将整数数组写入文件

[英]How to write array of integers into file in Java

I have an array of integers: 我有一个整数数组:

[56, 6090, 1510, 256, 17]

How do I write this into a file in append mode? 如何在追加模式下将其写入文件? I'll have many more arrays just like to write to the same file.. how do I append them line by line? 我将拥有更多的数组,就像要写入同一文件一样。如何将它们逐行追加?

I want my final file to look like this: 我希望我的最终文件看起来像这样:

A B C D E
56 6090 1510 256 17
60 42 3400 5499 12

How do I get this to work? 我该如何工作? How do I write the headers? 如何写标题?

I have this but my resulting file looks strange. 我有这个,但是我得到的文件看起来很奇怪。 What are those characters? 这些字符是什么?

    public static void main(String args[]) throws IOException {
            // input files
            String fileName = "SmallAreaIncomePovertyEstData.txt";
        File f = new File(fileName);

        // output files
        String tempFileName = "tempFile.txt";
        File outputf = new File(tempFileName);

        //writer to the output file
        BufferedWriter outputWriter = new BufferedWriter(new FileWriter(outputf, true));
        BufferedReader br = new BufferedReader(new FileReader(f));

          ...

            for(int i = 0; i < rowDataOnlyIntegers.length; i++) {
                outputWriter.write(rowDataOnlyIntegers[i]);
            }
            outputWriter.newLine();
        }
        br.close();
        outputWriter.close();

I suggest that you use a PrintWriter to write to a file instead. 我建议您改用PrintWriter写入文件。 The method write that you are calling writes a character encoded as the integer argument, not the string representation of the integer, which you have expected. 该方法write您呼叫写入编码为整数参数,而不是整数,你有预期的字符串表示一个字符 So write(32) would write a space character, because a space is encoded as 32 in UTF-16. 所以write(32)会写一个空格字符,因为在UTF-16中空格被编码为32。

PrintWriter allows you to directly write strings instead. PrintWriter允许您直接编写字符串。

Here's how to use a PrintWriter . 这是使用PrintWriter

String tempFileName = "tempFile.txt";
File outputf = new File(tempFileName);

//writer to the output file
PrintWriter outputWriter = new PrintWriter(outputf);

  ...

    for(int i = 0; i < rowDataOnlyIntegers.length; i++) {
        outputWriter.print(rowDataOnlyIntegers[i]);
        outputWriter.print(" ");
    }
    outputWriter.println();

You can use the Java 8 API to manipulate integer arrays and write lines into a file. 您可以使用Java 8 API操纵整数数组并将行写入文件中。 In my opinion, it's easier and cleaner. 在我看来,它更容易,更清洁。

The process of writing all the lines into a file is just one line of code (assuming that you don't load super large amount of data into the memory all at once): 将所有行写入文件的过程仅是一行代码(假设您不会一次将全部数据都加载到内存中):

void writeLines(Path file, List<String> lines) throws IOException {
    Files.write(file, lines, StandardOpenOption.APPEND);
}

Explanation and an example 说明和示例

Let's suppose you have a method that provides you with a list of integer arrays: 假设您有一个为您提供整数数组列表的方法:

List<int[]> getIntArrays() {
        int[] a1 = { 23, 54, 656, 332, 556 };
        int[] a2 = { 12, 45, 6556, 232, 323 };
        int[] a3 = { 898, 787, 23, 4545, 233 };
        return Arrays.asList(a1, a2, a3);
}

You can convert each array into a one-line string this way: 您可以通过以下方式将每个数组转换为单行字符串:

String toString(int[] array) {
    String DELIMITER = " ";
    return String.join(DELIMITER, IntStream.of(array)
                                  .mapToObj(a -> String.valueOf(a))
                                  .collect(Collectors.toList()));
}

The next method converts a list of integer arrays into a list of strings: 下一个方法将整数数组列表转换为字符串列表:

List<String> toString(List<int[]> arrays) {
    return arrays.stream().map(a -> toString(a)).collect(Collectors.toList());
}

This list can be fed to the writeLines method above and the lines will be written to a file. 可以将此列表提供给上面的writeLines方法,并将这些行写入文件中。

How do we write the header? 我们如何编写标题?

Here's a full example. 这是一个完整的例子。 It writes the header add all the lines of integers. 它写的标题加上所有整数行。

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ArrayWriter {

    private final static Charset UTF8 = Charset.forName("UTF-8");
    private final static String DELIMITER = " ";

    public static void main(String[] args) throws IOException {
        Path file = Paths.get("test.txt");
        writeHeader(file);
        writeLines(file, toString(getIntArrays()));
    }

    private static void writeHeader(Path file) throws IOException {
        String line = String.join(DELIMITER, getHeader());
        Files.write(file, Arrays.asList(line), UTF8, StandardOpenOption.CREATE);
    }

    private static void writeLines(Path file, List<String> lines) throws IOException {
        Files.write(file, lines, UTF8, StandardOpenOption.APPEND);
    }

    private static List<String> toString(List<int[]> arrays) {
        return arrays.stream().map(a -> toString(a)).collect(Collectors.toList());
    }

    private static String toString(int[] array) {
        return String.join(DELIMITER,
                IntStream.of(array).mapToObj(a -> String.valueOf(a)).collect(Collectors.toList()));
    }

    public static String[] getHeader() {
        return new String[] { "A", "B", "C", "D", "E" };
    }

    public static List<int[]> getIntArrays() {
        int[] a1 = { 23, 54, 656, 332, 556 };
        int[] a2 = { 12, 45, 6556, 232, 323 };
        int[] a3 = { 898, 787, 23, 4545, 233 };
        return Arrays.asList(a1, a2, a3);
    }
}

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

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