Reputation: 339
I want to write string array in .txt file. But after running my code, I am getting an empty file. Here is my code.
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();
}
}
What's wrong in my code I cannot understand.Compiler shows no error. Please Help. All answer would be appreciated.
Upvotes: 2
Views: 7188
Reputation: 5448
Here is another solution using Apache Camel route and StringUtils
of Spring Framework.
The class has a useful method: StringUtils.collectionToDelimitedString(list, delimiter)
which does most of the logic.
Note that you can also use the Spring StringUtils
class without Camel.
Here is a unit test which demonstrate the solution:
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();
}
Upvotes: 0
Reputation: 6017
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) {
}
}
You need to close the BufferedReader
. A better solution is using try-with-resources, so you don't need to worry about closing.
You can have multiple resources in the try-with-resources separated by a ;
.
Java 13+, you can use 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) {
}
}
You can also write your array in one line as:
String[] numberOfProperty = {"1", "2", "3"};
Upvotes: 6
Reputation: 337
First thing I realised is your method naming, try using camel casing. Instead of DataSave() try dataSave() for more information on Naming Conventions see this link: https://www.javatpoint.com/java-naming-conventions
Secondly when using java resources to read and or write to files be sure to close the resource when processing has finished. You can see more information on this here: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
See my example below with a try-with-resource Statement.
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());
}
}
Upvotes: 2