Write Array of String Arrays to File (txt,csv, etc) - java

I have an Arraylist of String Arrays called NewArray.
ArrayList<String[]> NewArray = new ArrayList<String[]>();
The data in NewArray looks somewhat like
[Vial1,Dest1]
[Vial2,Dest1]
[Vial3,Dest2]
[Vial4,Dest2]
I want to save this data, in this format (without the brackets) to a CSV/text file (with headers). The ideal output format would be:
VialNo,DestinationNo (these are the headers)
Vial1,Dest1
Vial2,Dest1
Vial3,Dest2
Vial4,Dest2
How would I use something like FileWriter to obtain that desired output in a txt/CSV file?
I've tried something like
FileWriter writer = new FileWriter("output.txt");
for(String[] str: NewArray) {
writer.write(str);
}
writer.close();
But I'm getting the error "The method write(int) in the type OutputStreamWriter is not applicable for the arguments (String[])"

public static void main(String[] args) throws Exception {
// initialize
ArrayList<String[]> list = new ArrayList<String[]>();
list.add(new String[] {"Vial1","Dest1"});
list.add(new String[] {"Vial2","Dest2"});
list.add(new String[] {"Vial3","Dest3"});
list.add(new String[] {"Vial4","Dest4"});
// writer
FileWriter writer = new FileWriter("output.txt");
// headers
writer.write("VialNo,DestinationNo\n");
writer.flush();
// data
for(String[] arr: list) {
String appender = "";
for(String s : arr){
writer.write(appender + s);
appender = ",";
}
writer.write("\n");
writer.flush();
}
writer.close();
}
This gave me the output
VialNo,DestinationNo
Vial1,Dest1
Vial2,Dest2
Vial3,Dest3
Vial4,Dest4
You need to loop over each string in each array, not try to simply print out the array. I also used an appender for formatting the file as a csv.
Updated code to include creating the headers

I would suggest you loop through your array and always write a line. Better put your writer in a using, so you don't have to bother with closing and flushing Streams, Writers etc.
If you actually want to save the object and not just write the content of the array down, then take a look at the serializer which outputs the object as xml which you can save to a file and load through a deserialize.

In case the accepted answer didn't work for someone (didn't for me). Try this for
ArrayList of specific class types foe example ArrayList tester = new ArrayList();
public class PassDataToFile {
public static void main(String[] args) throws IOException {
try {
RSSFeedParser parser = new RSSFeedParser("http://feeds.reuters.com/reuters/technologysectorNews");
Feed feed = parser.readFeed();
String input = "C:\\Users\\Special\\workspace\\demo.txt";
File newFile = new File(input);
if (!newFile.exists()){
newFile.createNewFile();
}
FileWriter writer = new FileWriter(newFile.getAbsoluteFile());
int sx = feed.getMessages().size();
for (int i = 0; i < sx; i++) {
writer.write(feed.getMessages().get(i).toString() + "\n");
}
writer.close();
System.out.println("File successfully written into " + input);
} catch (IOException e) {
System.out.println("File writing operation failed ");
e.printStackTrace();
}
}
}

Related

How can I read from the next line of a text file, and pause, allowing me to read from the line after that later?

I wrote a program that generates random numbers into two text files and random letters into a third according the two constant files. Now I need to read from each text file, line by line, and put them together. The program is that the suggestion found here doesn't really help my situation. When I try that approach it just reads all lines until it's done without allowing me the option to pause it, go to a different file, etc.
Ideally I would like to find some way to read just the next line, and then later go to the line after that. Like maybe some kind of variable to hold my place in reading or something.
public static void mergeProductCodesToFile(String prefixFile,
String inlineFile,
String suffixFile,
String productFile) throws IOException
{
try (BufferedReader br = new BufferedReader(new FileReader(prefixFile)))
{
String line;
while ((line = br.readLine()) != null)
{
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(productFile, true))))
{
out.print(line); //This will print the next digit to the right
}
catch (FileNotFoundException e)
{
System.err.println("File error: " + e.getMessage());
}
}
}
}
EDIT: The digits being created according to the following. Basically, constants tell it how many digits to create in each line and how many lines to create. Now I need to combine these together without deleting anything from either text file.
public static void writeRandomCodesToFile(String codeFile,
char fromChar, char toChar,
int numberOfCharactersPerCode,
int numberOfCodesToGenerate) throws IOException
{
for (int i = 1; i <= PRODUCT_COUNT; i++)
{
int I = 0;
if (codeFile == "inline.txt")
{
for (I = 1; I <= CHARACTERS_PER_CODE; I++)
{
int digit = (int)(Math.random() * 10);
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(codeFile, true))))
{
out.print(digit); //This will print the next digit to the right
}
catch (FileNotFoundException e)
{
System.err.println("File error: " + e.getMessage());
System.exit(1);
}
}
}
if ((codeFile == "prefix.txt") || (codeFile == "suffix.txt"))
{
for (I = 1; I <= CHARACTERS_PER_CODE; I++)
{
Random r = new Random();
char digit = (char)(r.nextInt(26) + 'a');
digit = Character.toUpperCase(digit);
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(codeFile, true))))
{
out.print(digit);
}
catch (FileNotFoundException e)
{
System.err.println("File error: " + e.getMessage());
System.exit(1);
}
}
}
//This will take the text file to the next line
if (I >= CHARACTERS_PER_CODE)
{
{
Random r = new Random();
char digit = (char)(r.nextInt(26) + 'a');
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(codeFile, true))))
{
out.println(""); //This will return a new line for the next loop
}
catch (FileNotFoundException e)
{
System.err.println("File error: " + e.getMessage());
System.exit(1);
}
}
}
}
System.out.println(codeFile + " was successfully created.");
}// end writeRandomCodesToFile()
Being respectfull with your code, it will be something like this:
public static void mergeProductCodesToFile(String prefixFile, String inlineFile, String suffixFile, String productFile) throws IOException {
try (BufferedReader prefixReader = new BufferedReader(new FileReader(prefixFile));
BufferedReader inlineReader = new BufferedReader(new FileReader(inlineFile));
BufferedReader suffixReader = new BufferedReader(new FileReader(suffixFile))) {
StringBuilder line = new StringBuilder();
String prefix, inline, suffix;
while ((prefix = prefixReader.readLine()) != null) {
//assuming that nothing fails and the files are equals in # of lines.
inline = inlineReader.readLine();
suffix = suffixReader.readLine();
line.append(prefix).append(inline).append(suffix).append("\r\n");
// write it
...
}
} finally {/*close writers*/}
}
Some exceptions may be thrown.
I hope you don't implement it in one single method.
You can make use of iterators too, or a very simple reader class (method).
I wouldn't use List to load the data at least I guarantee that the files will be low sized and that I can spare the memory usage.
My approach as we discussed by storing the data and interleaving it. Like Sergio said in his answer, make sure memory isn't a problem in terms of the size of the file and how much memory the data structures will use.
//the main method we're working on
public static void mergeProductCodesToFile(String prefixFile,
String inlineFile,
String suffixFile,
String productFile) throws IOException
{
try {
List<String> prefix = read(prefixFile);
List<String> inline = read(inlineFile);
List<String> suffix = read(productFile);
String fileText = interleave(prefix, inline, suffix);
//write the single string to file however you want
} catch (...) {...}//do your error handling...
}
//helper methods and some static variables
private static Scanner reader;//I just prefer scanner. Use whatever you want.
private static StringBuilder sb;
private static List<String> read(String filename) throws IOException
{
List<String> list = new ArrayList<String>;
try (reader = new Scanner(new File(filename)))
{
while(reader.hasNext())
{ list.add(reader.nextLine()); }
} catch (...) {...}//catch errors...
}
//I'm going to build the whole file in one string, but you could also have this method return one line at a time (something like an iterator) and output it to the file to avoid creating the massive string
private static String interleave(List<String> one, List<String> two, List<String> three)
{
sb = new StringBuilder();
for (int i = 0; i < one.size(); i++)//notice no checking on size equality of words or the lists. you might want this
{
sb.append(one.get(i)).append(two.get(i)).append(three.get(i)).append("\n");
}
return sb.toString()
}
Obviously there is still some to be desired in terms of memory and performance; additionally there are ways to make this slightly more extensible to other situations, but it's a good starting point. With c#, I could more easily make use of the iterator to make interleave give you one line at a time, potentially saving memory. Just a different idea!

Java: Methods, Files, and Arrays

I'm supposed to be coding an app that can read names from a hardcoded text file, save them as a string array, then write those names in a different text file but sorted. I believe I have the first two parts down but I'm confused on how to sort the names then write them into a new file.
These is the actual problem I'm working on:
"Take an input file with 10 names in it (hard coded). Write a program to read the file, save the names in a String array and write into a different file names in sorted order. Use Methods appropriately."
BTW I'm a rookie coder, this is what I have so far.
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
readFile();
saveStringArray();
}
public static void readFile() {
File file = new File("/Users/nicoladaaboul/Desktop/Programming/C++, "
+ "HTML5, Java, PHP/Java/Question2/names.txt");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String i = sc.next();
}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void saveStringArray() throws FileNotFoundException {
String token1 = "";
Scanner inFile1 = new Scanner(new File("names.txt")).useDelimiter(",\\s*");
List<String> temps = new ArrayList<String>();
while (inFile1.hasNext()) {
token1 = inFile1.next();
temps.add(token1);
}
inFile1.close();
String[] tempsArray = temps.toArray(new String[0]);
Arrays.sort(tempsArray);
for (String s : tempsArray) {
System.out.println(s);
}
}
public static void sortingNames() {
}
public static void writingFile() throws FileNotFoundException {
PrintWriter writer = new PrintWriter("sortedNames.txt");
writer.close();
}
Its important that you break your problem down into instructions.
1. You need to read the file you can use bufferedReader(code below).
2. Create an array(or arraylist) to store your string values.
3. Then as you read each line, store these values in the array.
4. When finished reading the file you then would pass this array to a function that would sort it(Why does my sorting loop seem to append an element where it shouldn't?).
5. Once sorted you simply write this array, to a file.
BufferedReader br = new BufferReader(new FileReader("name.txt"));
int count = 0;
String line;
String[] names = new String[100];
while((line = br.nextLine()) != null){
names[count] = line;
count++;
}

OpenNLP - Tokenize an Array of Strings

I am trying to tokenize a text file using the OpenNLP tokenizer.
What I do, I read in a .txt file and store it in a list, want to iterate over every line, tokenize the line and write the tokenized line to a new file.
In the line:
tokens[i] = tokenizer.tokenize(output[i]);
I get:
Type mismatch: cannot convert from String[] to String
This is my code:
public class Tokenizer {
public static void main(String[] args) throws Exception {
InputStream modelIn = new FileInputStream("en-token-max.bin");
try {
TokenizerModel model = new TokenizerModel(modelIn);
Tokenizer tokenizer = new TokenizerME(model);
CSVReader reader = new CSVReader(new FileReader("ParsedRawText1.txt"),',', '"', 1);
String csv = "ParsedRawText2.txt";
CSVWriter writer = new CSVWriter(new FileWriter(csv),CSVWriter.NO_ESCAPE_CHARACTER,CSVWriter.NO_QUOTE_CHARACTER);
//Read all rows at once
List<String[]> allRows = reader.readAll();
for(String[] output : allRows) {
//get current row
String[] tokens=new String[output.length];
for(int i=0;i<output.length;i++){
tokens[i] = tokenizer.tokenize(output[i]);
System.out.println(tokens[i]);
}
//write line
writer.writeNext(tokens);
}
writer.close();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (modelIn != null) {
try {
modelIn.close();
}
catch (IOException e) {
}
}
}
}
}
Does anyone has any idea how to complete this task?
As compiler says, you try to assign array of Strings (result of tokenize()) to String (tokens[i] is a String). So you should declare and use tokens inside the inner loop and write tokens[] there, too:
for (String[] output : allRows) {
// get current row
for (int i = 0; i < output.length; i++) {
String[] tokens = tokenizer.tokenize(output[i]);
System.out.println(tokens);
// write line
writer.writeNext(tokens);
}
}
writer.close();
Btw, are you sure that your source file is a csv? If it is actually a plain text file, then you split text by commas and gives such chunks to Opennlp, and it can perform worse, because its model was trained over normal sentences, not split like yours.

Java: Reading txt file into a 2D array

For homework, we have to read in a txt file which contains a map. With the map we are supposed to read in its contents and place them into a two dimensional array.
I've managed to read the file into a one dimensional String ArrayList, but the problem I am having is with converting that into a two dimensional char array.
This is what I have so far in the constructor:
try{
Scanner file=new Scanner (new File(filename));
while(file.hasNextLine()){
ArrayList<String> lines= new ArrayList<String>();
String line= file.nextLine();
lines.add(line);
map=new char[lines.size()][];
}
}
catch (IOException e){
System.out.println("IOException");
}
When I print out the lines.size() it prints out 1 but when I look at the file it has 10.
Thanks in advance.
You have to create the list outside the loop. With your actual implementation, you create a new list for each new line, so it will always have size 1.
// ...
Scanner file = new Scanner(new File(filename));
List<String> lines = new ArrayList<String>(); // <- declare lines as List
while(file.hasNextLine()) {
// ...
BTW - I wouldn't name the char[][] variable map. A Map is a totally different data structure. This is an array, and if you create in inside the loop, then you may encounter the same problems like you have with the list. But now you should know a quick fix ;)
Change the code as following:
public static void main(String[] args) {
char[][] map = null;
try {
Scanner file = new Scanner(new File("textfile.txt"));
ArrayList<String> lines = new ArrayList<String>();
while (file.hasNextLine()) {
String line = file.nextLine();
lines.add(line);
}
map = new char[lines.size()][];
} catch (IOException e) {
System.out.println("IOException");
}
System.out.println(map.length);
}

How to write an ArrayList of Strings into a text file?

I want to write an ArrayList<String> into a text file.
The ArrayList is created with the code:
ArrayList arr = new ArrayList();
StringTokenizer st = new StringTokenizer(
line, ":Mode set - Out of Service In Service");
while(st.hasMoreTokens()){
arr.add(st.nextToken());
}
import java.io.FileWriter;
...
FileWriter writer = new FileWriter("output.txt");
for(String str: arr) {
writer.write(str + System.lineSeparator());
}
writer.close();
You can do that with a single line of code nowadays.
Create the arrayList and the Path object representing the file where you want to write into:
Path out = Paths.get("output.txt");
List<String> arrayList = new ArrayList<> ( Arrays.asList ( "a" , "b" , "c" ) );
Create the actual file, and fill it with the text in the ArrayList:
Files.write(out,arrayList,Charset.defaultCharset());
I would suggest using FileUtils from Apache Commons IO library.It will create the parent folders of the output file,if they don't exist.while Files.write(out,arrayList,Charset.defaultCharset()); will not do this,throwing exception if the parent directories don't exist.
FileUtils.writeLines(new File("output.txt"), encoding, list);
If you need to create each ArrayList item in a single line then you can use this code
private void createFile(String file, ArrayList<String> arrData)
throws IOException {
FileWriter writer = new FileWriter(file + ".txt");
int size = arrData.size();
for (int i=0;i<size;i++) {
String str = arrData.get(i).toString();
writer.write(str);
if(i < size-1)**//This prevent creating a blank like at the end of the file**
writer.write("\n");
}
writer.close();
}
If you want to serialize the ArrayList object to a file so you can read it back in again later use ObjectOuputStream/ObjectInputStream writeObject()/readObject() since ArrayList implements Serializable. It's not clear to me from your question if you want to do this or just write each individual item. If so then Andrey's answer will do that.
You might use ArrayList overloaded method toString()
String tmp=arr.toString();
PrintWriter pw=new PrintWriter(new FileOutputStream(file));
pw.println(tmp.substring(1,tmp.length()-1));
I think you can also use BufferedWriter :
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("note.txt")));
String stuffToWrite = info;
writer.write(stuffToWrite);
writer.close();
and before that remember too add
import java.io.BufferedWriter;
Write a array list to text file using JAVA
public void writeFile(List<String> listToWrite,String filePath) {
try {
FileWriter myWriter = new FileWriter(filePath);
for (String string : listToWrite) {
myWriter.write(string);
myWriter.write("\r\n");
}
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}

Categories

Resources