java 如何在 .txt 文件中写入或存储字符串数组
How to write or store string array in .txt file in java
我想在 .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();
}
}
我的代码有什么问题我不能understand.Compiler没有显示错误。请帮忙。所有答案将不胜感激。
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"};
我首先意识到你的方法命名,尝试使用驼峰式大小写。尝试使用 dataSave() 而不是 DataSave() 以获取有关命名约定的更多信息,请参阅此 link: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());
}
}
这是另一个使用 Apache Camel 路由和 Spring 框架的 StringUtils
的解决方案。
class 有一个有用的方法:StringUtils.collectionToDelimitedString(list, delimiter)
可以完成大部分逻辑。
请注意,您也可以使用不带 Camel 的 Spring StringUtils
class。
这是一个演示解决方案的单元测试:
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();
}
我想在 .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();
}
}
我的代码有什么问题我不能understand.Compiler没有显示错误。请帮忙。所有答案将不胜感激。
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"};
我首先意识到你的方法命名,尝试使用驼峰式大小写。尝试使用 dataSave() 而不是 DataSave() 以获取有关命名约定的更多信息,请参阅此 link: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());
}
}
这是另一个使用 Apache Camel 路由和 Spring 框架的 StringUtils
的解决方案。
class 有一个有用的方法:StringUtils.collectionToDelimitedString(list, delimiter)
可以完成大部分逻辑。
请注意,您也可以使用不带 Camel 的 Spring StringUtils
class。
这是一个演示解决方案的单元测试:
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();
}