Trying to save arraylist items to a text file, I kind of have it working but it saves the whole arraylist on one line
I am hoping to save it per line and not have any duplicates or the empty brackets at the start, Any help would be much appreciated. Also if possible to remove the brackets around the text for easier reading into an arraylist
FileOutputStream is more fitting for when your data is already in a byte format. I suggest you use something like a PrintWriter.
PrintWriter pw = null;
try {
File file = new File("file.txt"); //edited
pw = new PrintWriter(file); //edited
for(String item: Subreddit_Array_List)
pw.println(item);
} catch (IOException e) {
e.printStackTrace();
}
finally{
pw.close();
}
Keep in mind this overwrites what was in the file before rather than appends to it. The output will be formatted like:
Cats
Dogs
Birds
You can iterate over the map and save all variables in separate lines.
Example:
private List<Object> objects;
private void example() {
//JDK >= 8
this.objects.forEach(this::writeInFile);
//JDK < 8
for (Object object : this.objects) {
this.writeInFile(object);
}
}
private void writeInFile(Object object) {
//your code here
}
Related
I am a beginner and I am trying to read a .tsv data in Java and save the lines to an ArrayList. I wrote a method for it but the only thing I get is line id's and nothing more... I can't find an error. Could you please help me?
public static ArrayList<String[]> tsvr(File test2) throws IOException {
BufferedReader TSVReader = new BufferedReader(new FileReader(test2));
String line = TSVReader.readLine();
ArrayList<String[]> Data = new ArrayList<>(); //initializing a new ArrayList out of String[]'s
try {
while (line != null) {
String[] lineItems = line.split("\n"); //splitting the line and adding its items in String[]
Data.add(lineItems); //adding the splitted line array to the ArrayList
line = TSVReader.readLine();
} TSVReader.close();
} catch (Exception e) {
System.out.println("Something went wrong");
}
return Data;
}
First, you should move readLine to a while, so that you can read all the lines of the file. Then you should split the line by tab \t because it is a tab separated file
public static ArrayList<String[]> tsvr(File test2) {
ArrayList<String[]> Data = new ArrayList<>(); //initializing a new ArrayList out of String[]'s
try (BufferedReader TSVReader = new BufferedReader(new FileReader(test2))) {
String line = null;
while ((line = TSVReader.readLine()) != null) {
String[] lineItems = line.split("\t"); //splitting the line and adding its items in String[]
Data.add(lineItems); //adding the splitted line array to the ArrayList
}
} catch (Exception e) {
System.out.println("Something went wrong");
}
return Data;
}
If you want to print the list of array:
Data.forEach(array -> System.out.println(Arrays.toString(array)));
Explanation
You have to split on \t (tab) instead of \n (newline). As your lines are already single lines, not multiple.
Another issue in your code is that you close your stream manually, this is unsafe and will create a resource leak in exception-case. You may use try-with-resources to close it safely.
NIO
Instead of fixing your existing code which other answers already did, may I suggest a more compact and possibly more readable version that uses NIO (Java 8 or newer) which does the same:
return Files.lines(file.toPath())
.map(line -> line.split("\t"))
.collect(Collectors.toList());
If you can modernize your method parameters, I would suggest to make it Path path instead of File file, then you can simply do Files.lines(path)
I wrote a simple program to read the content from text/log file to html with conditional formatting.
Below is my code.
import java.io.*;
import java.util.*;
class TextToHtmlConversion {
public void readFile(String[] args) {
for (String textfile : args) {
try{
//command line parameter
BufferedReader br = new BufferedReader(new FileReader(textfile));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
Date d = new Date();
String dateWithoutTime = d.toString().substring(0, 10);
String outputfile = new String("Test Report"+dateWithoutTime+".html");
FileWriter filestream = new FileWriter(outputfile,true);
BufferedWriter out = new BufferedWriter(filestream);
out.write("<html>");
out.write("<body>");
out.write("<table width='500'>");
out.write("<tr>");
out.write("<td width='50%'>");
if(strLine.startsWith(" CustomerName is ")){
//System.out.println("value of String split Client is :"+strLine.substring(16));
out.write(strLine.substring(16));
}
out.write("</td>");
out.write("<td width='50%'>");
if(strLine.startsWith(" Logged in users are ")){
if(!strLine.substring(21).isEmpty()){
out.write("<textarea name='myTextBox' cols='5' rows='1' style='background-color:Red'>");
out.write("</textarea>");
}else{
System.out.println("else if block:");
out.write("<textarea name='myTextBox' cols='5' rows='1' style='background-color:Green'>");
out.write("</textarea>");
} //closing else block
//out.write("<br>");
out.write("</td>");
}
out.write("</td>");
out.write("</tr>");
out.write("</table>");
out.write("</body>");
out.write("</html>");
out.close();
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
public static void main(String args[]) {
TextToHtmlConversion myReader = new TextToHtmlConversion();
String fileArray[] = {"D:/JavaTesting/test.log"};
myReader.readFile(fileArray);
}
}
I was thinking to enhance my program and the confusion is of either i should use Maps or properties file to store search string. I was looking out for a approach to avoid using substring method (using index of a line). Any suggestions are truly appreciated.
From top to bottom:
Don't use wildcard imports.
Don't use the default package
restructure your readFile method in more smaller methods
Use the new Java 7 file API to read files
Try to use a try-block with a resource (your file)
I wouldn't write continuously to a file, write it in the end
Don't catch general Exception
Use a final block to close resources (or the try block mentioned before)
And in general: Don't create HTML by appending strings, this is a bad pattern for its own. But well, it seems that what you want to do.
Edit
Oh one more: Your text file contains some data right? If your data represents some entities (or objects) it would be good to create a POJO for this. I think your text file contains users (right?). Then create a class called Users and parse the text file to get a list of all users in it. Something like:
List<User> users = User.parse("your-file.txt");
Afterwards you have a nice user object and all your ugly parsing is in one central point.
I have a .txt file which contains a list of stuff I want to store in an Array and use throughout my application. To achieve this I created the following class:
public class Sort {
ArrayList<String> sorted = new ArrayList<String>();
public Sort() throws IOException {
Scanner scanner = new Scanner(new FileReader("/home/scibor/coding/src/com/myapp/readThis.txt"));
while(scanner.hasNextLine()){
sorted.add(scanner.nextLine());
}
}
}
So I have a .txt file with a bunch of stuff in it, and then I create this class specifically for that case. Now when I want to access these things in the .txt file in an ArrayList in one of my other classes, I figure:
Sort sort = new Sort();
sort.sorted; //can use the arrayList like so
Instead I get a message that says UnhandledException: java.io.IOException
I've tried several variations of this using try/catch, BufferedReader with try/catch/finally and ultimately all of them have some sort of error pertaining to the Exceptions that are raised by reading in a file. What am I doing wrong here?
EDIT: As per one of the suggestions, I have tried a radically different approach as below:
public class Sort {
List<String> sorted;
public Sort(Context context){
sorted = new ArrayList<String>();
AssetManager assetManager = context.getAssets();
try {
InputStream read = assetManager.open("readThis.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(read));
while(reader.readLine() != null){
sorted.add(reader.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This seems to get me further, and is probably very close to the correct answer. When I create Sort mySortedObject = new Sort(this); there are no errors generated. When I finally access the ArrayList though, as follows:
for(String name: mySortedObject.sort){
if(name.equals("Whatever"){
//run this
}
}
}
I get a NullPointerException on the line containing the if statement. So the object was successfully created...but not quite?
EDIT: The "readThis.txt" file is located in /assets
I believe the file "/home/scibor/coding/src/com/myapp/readThis.txt" does not exist on your phone (and for a good reason). You will need to add your .txt as an asset to your project and load it using the AssetManager.open()-method
Edit:
In your edited code, your NullPointerException is caused by you calling .readLine() twice in each iteration.
Solution:
String line = null;
while(true){
line = reader.readLine();
if (line == null) break;
sorted.add(line);
}
I'm having memory problem as working with very large dataset and getting memory leaks with char[] and Strings, don't know why! So I am thinking of writing some processed data in a file and not store in memory. So, I want to write texts from an arrayList in a file using a loop. First the program will check if the specific file already exist in the current working directory and if not then create a file with the specific name and start writing texts from the arrayList line by line using a loop; and if the file is already exist then open the file and append the 1st array value after the last line(in a new line) of the file and start writing other array values in a loop line by line.
Can any body suggest me how can I do this in Java? I'm not that good in Java so please provide some sample code if possible.
Thanks!
I'm not sure what parts of the process you are unsure of, so I'll start at the beginning.
The Serializable interface lets you write an object to a file. Any object that implemsents Serializable can be passed to an ObjectOutputStream and written to a file.
ObjectOutputStream accepts a FileOutputStream as argument, which can append to a file.
ObjectOutputstream outputStream = new ObjectOutputStream(new FileOutputStream("filename", true));
outputStream.writeObject(anObject);
There is some exception handling to take care of, but these are the basics. Note that anObject should implement Serializable.
Reading the file is very similar, except it uses the Input version of the classes I mentioned.
Try this
ArrayList<String> StringarrayList = new ArrayList<String>();
FileWriter writer = new FileWriter("output.txt", true);
for(String str: StringarrayList ) {
writer.write(str + "\n");
}
writer.close();
// in main
List<String> SarrayList = new ArrayList<String>();
.....
fill it with content
enter content to SarrayList here.....
write to file
appendToFile (SarrayList);
.....
public void appendToFile (List<String> SarrayList) {
BufferedWriter bw = null;
boolean myappend = true;
try {
bw = new BufferedWriter(new FileWriter("myContent.txt", myappend));
for(String line: SarrayList ) {
bw.write(line);
bw.newLine();
}
bw.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (bw != null) try {
bw.close();
} catch (IOException ioe2) {
// ignore it or write notice
}
}
}
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();
}
}