【问题标题】:How to write or store string array in .txt file in java如何在java中的.txt文件中写入或存储字符串数组
【发布时间】:2020-08-22 09:26:19
【问题描述】:

我想在 .txt 文件中写入字符串数组。但是在运行我的代码后,我得到一个空文件。这是我的代码。

public void DataSave() throws IOException {
        File fout = new File("Data.txt");
        FileOutputStream fos = new FileOutputStream(fout);

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

        String[] numberOfProperty = new String[3];
        numberOfProperty[0] = "1";
        numberOfProperty[1] = "3";
        numberOfProperty[2] = "4";
        for (int i = 0; i < numberOfProperty.length; i++) {
            bw.write(numberOfProperty[i]);
            bw.newLine();
        }
    }

我无法理解我的代码有什么问题。编译器没有显示错误。请帮忙。所有答案将不胜感激。

【问题讨论】:

  • 最后需要关闭 writer。
  • 您应该关闭 BufferedWritter 或使用“try with resources”
  • 可能缓冲区没有被刷新。 close可以做到。

标签: java arrays string filewriter bufferedwriter


【解决方案1】:
public void DataSave() {
    File fout = new File("Data.txt");
    try (FileOutputStream fos = new FileOutputStream(fout); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));) {
        String[] numberOfProperty = new String[3];
        numberOfProperty[0] = "1";
        numberOfProperty[1] = "3";
        numberOfProperty[2] = "4";
        for (String s : numberOfProperty) {
            bw.write(s);
            bw.newLine();
        }
    } catch (IOException ignored) {

    }
}

您需要关闭BufferedReader。更好的解决方案是使用 try-with-resources,因此您无需担心关闭。

try-with-resources 中可以有多个资源,由 ; 分隔。


Java 13+,可以使用Path.of()

public void DataSave() {
    File fout = new File("Data.txt");
    try (FileOutputStream fos = new FileOutputStream(fout); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));) {
        String[] numberOfProperty = new String[3];
        numberOfProperty[0] = "1";
        numberOfProperty[1] = "3";
        numberOfProperty[2] = "4";
        Files.write(Path.of("Data.txt"), Collections.singletonList(numberOfProperty));
    } catch (IOException ignored) {

    }
}

你也可以将你的数组写成一行:

String[] numberOfProperty = {"1", "2", "3"};

【讨论】:

  • Files.write(Path.of("Data.txt"), Arrays.asList(numberOfProperty)); 更短。
【解决方案2】:

我意识到的第一件事是你的方法命名,尝试使用骆驼套管。代替 DataSave() 尝试 dataSave() 以获取有关命名约定的更多信息,请参阅此链接:https://www.javatpoint.com/java-naming-conventions

其次,当使用 java 资源读取和或写入文件时,请务必在处理完成后关闭资源。您可以在此处查看更多信息:https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

请参阅下面带有 try-with-resource 语句的示例。

public void dataSave() {

    File fout = new File("data.txt");

    String[] numberOfProperty = new String[3];
    numberOfProperty[0] = "1";
    numberOfProperty[1] = "3";
    numberOfProperty[2] = "4";

    try (FileWriter fileWriter = new FileWriter(fout);
         BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)){

        for(String str: numberOfProperty)
        {
            bufferedWriter.write(str);
            bufferedWriter.newLine();

        }
    } catch (FileNotFoundException e) {
        System.out.println("Unable to open file, file not found.");
    } catch (IOException e) {
        System.out.println("Unable to write to file." + fout.getName());

    }

    }

【讨论】:

    【解决方案3】:

    这是另一个使用 Apache Camel 路由和 Spring Framework 的StringUtils 的解决方案。

    该类有一个有用的方法:StringUtils.collectionToDelimitedString(list, delimiter),它完成了大部分逻辑。

    请注意,您也可以在没有 Camel 的情况下使用 Spring StringUtils 类。

    这是一个演示解决方案的单元测试:

    package test.unit.camel;
    
    import org.apache.camel.Endpoint;
    import org.apache.camel.EndpointInject;
    import org.apache.camel.Processor;
    import org.apache.camel.builder.RouteBuilder;
    import org.apache.camel.component.mock.MockEndpoint;
    import org.apache.camel.test.junit4.CamelTestSupport;
    import org.apache.commons.io.FileUtils;
    import org.hamcrest.Matchers;
    import org.junit.Rule;
    import org.junit.Test;
    import org.junit.rules.TemporaryFolder;
    import org.springframework.util.StringUtils;
    
    import java.io.File;
    import java.util.List;
    
    public class StringToTextFileTest extends CamelTestSupport {
    
    @EndpointInject(uri = "direct:in")
    private Endpoint in;
    
    @EndpointInject(uri = "mock:error")
    private MockEndpoint error;
    
    @Test
    public void testString() throws Exception {
        error.expectedMessageCount(0);
    
        String[] numberOfProperty = new String[3];
        numberOfProperty[0] = "1";
        numberOfProperty[1] = "3";
        numberOfProperty[2] = "4";
    
    /*
        // This test the entry with a collection instead an array.
        List<String> numberOfProperty = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            numberOfProperty.add(String.valueOf(i+1));
        }
    */
        template.sendBody(in, numberOfProperty);
        assertMockEndpointsSatisfied();
    
        File[] files = testFolder.getRoot().listFiles();
        assertThat(files.length, Matchers.greaterThan(0));
        File result = files[0];
        assertThat(result.getName(), Matchers.is("file.txt"));
    
        String resultStr = FileUtils.readFileToString(result);
        log.info("Result string is: {}", resultStr);
    }
    
    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
    
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
    
                //@formatter:off
    
                onException(Exception.class)
                    .to("mock:error");
    
                from(in.getEndpointUri())
                    .process(processBody())
                    .to("file:" + testFolder.getRoot().getAbsolutePath() + "?fileName=file.txt")
                ;
                //@formatter:on
            }
    
            private Processor processBody() {
                return exchange -> {
                    // Camel automatically converts arrays to Collection if needed. 
                    List<String> list = exchange.getIn().getBody(List.class);
                    String body = StringUtils.collectionToDelimitedString(list, "\n");
                    exchange.getIn().setBody(body);
                };
            }
        };
    }
    
    @Rule
    public TemporaryFolder testFolder = new TemporaryFolder();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-17
      相关资源
      最近更新 更多