Appending a set with a text file - java

If I have a result stored in the following set:
Set<Integer> dataset = new HashSet<>();
Also, I have this text file:
File file = new File("\Users\Test.txt");
My goal is to append the set dataset with the Test.txt (Write it at the end of Test.txt or possibly append both to a new text file). I tried first to wrap my dataset using BufferedReader so I can prepare it for appending but I got stuck because the InputStreamReader does not accept Sets. I don't know how to fix it to proceed:
InputStream is = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(dataset)); // Error Here
Thank you for any help.

You should proceed like this:
Set<Integer> dataset = new HashSet<>();
dataset.add(8);
dataset.add(3);
dataset.add(7);
try (FileWriter fw = new FileWriter("\\Users\\Test.txt", true); // true -> append
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)) {
out.println(dataset);
} catch (IOException e) {
System.err.println("An exception occured: " + e.getMessage());
}
Note that we used a try with resources to automatically close the closable that were open in the try part.

I think there is an error in the path, you have to escape the '\':
File file = new File("\\Users\\Test.txt");

Related

New Line while writing into file

I followed this link and I came up with below code
try {
File file = new File(
"C:/dataset.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
List<Integer> data = generateData(args);
// one per line
for (final int i : data) {
bw.write(i);
bw.newLine(); // Here it throws NullPointerException
}
bw.close();
} catch (IOException e) {
System.out.print(e);
}
NOTE: Even if I move bw.newLine(); before for loop, it throws NullPointerException.
Image
Am I missing anything ?
To add a line seperator you could use this.
//to add a new line after each value added to File
String newLine = System.getProperty("line.separator");
and then call it like so:
bw.write(newLine);
EDIT:
since you cant use a System.getProperty with a BufferWriter I would suggest the code below:
private FileOutputStream fOut;
private OutputStreamWriter writer;
fOut = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
writer = new OutputStreamWriter(fOut);
writer.append(.... whatever you wish to append ...);
writer.append(separator);
writer.flush();
fOut.close();
Hope that helps!

Lists and Files

How to write a list in a file using JAVA?
I am writing a program to search files in a directory and display it. I also have a condition that I should store the search result in a log file. So please help me doing this.
From comments:
public void saveSearchResult(List<String> SearchResult) throws FileNotFoundException {
File file1 = new File("D://result.log");
FileInputStream in = new FileInputStream("D://result.log");
FileOutputStream out = new FileOutputStream(file1);
DataInputStream din = new DataInputStream(in);
DataOutputStream dout = new DataOutputStream(out);
for (String search : getSearchResult()) {
//Not getting hw to do this
}
}
Place your results into a string. Then load it into the file as follows...
StringBuilder s = new StringBuilder();
for (String search : getSearchResult()) {
s.append(search); //add formatting here as desired
}
try (FileWriter t = new FileWriter(new File("result.log"))) {
t.write(s.toString());
} catch (Exception e) {
System.out.println(e.getMessage());
}
You should always use a try with resources statement as above because it will insure the resources are released. http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
For a growing string you should use StringBuilder.
You probably want to create multiple new log files in which case I would suggest replacing "result.log" with this following code
new SimpleDateFormat("YYYY-MM-dd_hh-mm-ss").format(new Date(
System.currentTimeMillis())) + ".log"
This will output your log files so it looks like this...
result_2014-02-13_5-19-44.log
year/month/day/hour/minute/second

Writing to file in Java

First things first, I am a novice when it comes to Java. I have set myself a little project and I am currently stuck. I am trying to write to a file that already exists, but it just overwrites it. I am trying to replace the line that contains 'maxBooks'.
Here is the code than I am using:
FileWriter writeFile = new FileWriter(fileLocation);
BufferedReader readLines = new BufferedReader(new FileReader(fileLocation));
BufferedWriter writeLines = new BufferedWriter(writeFile);
System.out.println("\n-----File Begin-----");
while((finalLines = readLines.readLine()) != null){
if(finalLines.contains("maxBooks")){
writeLines.newLine();
writeLines.write(finalLines);
System.out.println("This is the if statement");
System.out.println(finalLines);
} else {
fileLines.add(new String(finalLines));
System.out.println("This is the else statement");
System.out.println(finalLines);
}
}
System.out.println("------File End------");
Please bear in mind that I have left out the try and catch. Please let me know how I can edit the text file. Let me know if you need any more info
Thanks :)
EDIT
Sorry, I should clarify. I am just trying to edit 1 line that is in the test file, not the whole text file.
FINAL CODE:
FileWriter writeFile = new FileWriter(fileLocation + ".tmp", true);
BufferedWriter writeLines = new BufferedWriter(writeFile);
BufferedReader readLines = new BufferedReader(new FileReader(fileLocation));
System.out.println("\n-----File Begin-----");
while((finalLines = readLines.readLine()) != null){
if(finalLines.contains("maxBooks")){
writeLines.write("maxBooks = " + maxBooks);
writeLines.newLine();
System.out.println("This is the if statement");
System.out.println(finalLines);
} else {
fileLines.add(new String(finalLines));
System.out.println("This is the else statement");
writeLines.write(finalLines);
writeLines.newLine();
}
}
System.out.println("------File End------");
file2.renameTo(file);
writeLines.close();
You overwrite the file you try to read, which is bad practice. Write to a new file, then rename to the original file.
you read and write on the same fileLocation you're supposed to give two differend locations;
goes something like this
//define newLocation as string that contain path for new file to be written
FileWriter writeFile = new FileWriter(newLocation);
BufferedReader readLines = new BufferedReader(new FileReader(fileLocation));
BufferedWriter writeLines = new BufferedWriter(writeFile);

Saving String Input on Android

Right, I've been trying to find a solution to this for a good while, but it's just not working for some reason.
In short, what I want to do is save every input String the user inputs into a file. Every time the activity is created again, I want to re-input these strings into a new instance of an object.
This code is what I use to create the file and read info from it, used in the onCreate() method of activity
try {
String brain = "brain";
File file = new File(this.getFilesDir(), brain);
if (!file.exists()) {
file.createNewFile();
}
BufferedReader in = new BufferedReader(new FileReader(file));
String s; // This feeds the object MegaAndroid with the strings, sequentially
while ((s = in.readLine()) != null) {
MegaAndroid.add(s);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
After that, every time the user inputs some text, the strings are saved onto the file:
try {
String brain = "brain";
File file = new File(this.getFilesDir(), brain);
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(message); // message is a string that holds the user input
out.close();
} catch (IOException e) {
e.printStackTrace();
}
For some reason, however, every time the application is killed, the data is lost.
What am I doing wrong?
EDIT: Also, if I were to access this file from another class, how can I?
As we discussed in the commend section the chief problem with the code is that your execution of FileWriter occurred prior to your FileReader operation while truncating the file. For you to maintain the file contents you want to set the write operation to an append:
BufferedWriter out = new BufferedWriter(new FileWriter(file,true));
out.write(message);
out.newLine();
out.close();
However, if every entry on the EditText is received then shipped into the file you'll just be writing data byte after byte beside it. It is easy to get contents similar to
This is line #1This is line #2
Instead of the desired
This is line #1
This is line #2
which would be corrected by having the BufferedWriter pass a newline after each write to the file.
This is what I do for file reading.
try{
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/whereyouwantfile");
dir.mkdirs();
Log.d(TAG,"path: "+dir.getAbsolutePath());
File file = new File(dir, "VERSION_FILENAME");
FileInputStream f = new FileInputStream(file);
//FileInputStream fis = context.openFileInput(VERSION_FILENAME);
BufferedReader reader = new BufferedReader(new InputStreamReader(f));
String line = reader.readLine();
Log.d(TAG,"first line versions: "+line);
while(line != null){
Log.d(TAG,"line: "+line);
//Process line how you need
line = reader.readLine();
}
reader.close();
f.close();
}
catch(Exception e){
Log.e(TAG,"Error retrieving cached data.");
}
And the following for writing
try{
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/whereyouwantfile");
dir.mkdirs();
File file = new File(dir, "CONTENT_FILENAME");
FileOutputStream f = new FileOutputStream(file);
//FileOutputStream fos = context.openFileOutput(CONTENT_FILENAME, Context.MODE_PRIVATE);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(f));
Set<String> keys = Content.keySet();
for(String key : keys){
String data = Content.get(key);
Log.d(TAG,"Writing: "+key+","+data);
writer.write(data);
writer.newLine();
}
writer.close();
f.close();
}
catch(Exception e){
e.printStackTrace();
Log.e(TAG,"Error writing cached data.");
}
You can use the private mode if you don't want the rest of the world to be able to see your files, but it is often useful to see them when debugging.

How to combine these two xml files

File employe = new File("E:five/emplo.xml");
File stud = new File("E:/one/two/student.xml");
how to combine these two files in one file object
If you want to merge two standard text files then you can just use filewriters and filereaders.
I assuming that this is not some xml specific thing as I am not experienced with them.
Here is how to read a file (without the exception handling):
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr); // the only reason I use this is because I am used to line by line handling
String line;
while((line = br.readLine()) != null)
{
// do something with each line
}
You could read each file into an arraylist of strings then output using:
FileWriter fout = new FileWriter(file, toAppend);
fout.write(msg);
fout.close();
String[] filenames = new String[]{ "emplo.xml", "student.xml"};
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream("merged.xml");
for (String filename : filenames) {
InputStream inputStream = new BufferedInputStream(new FileInputStream(filename);
org.apache.commons.io.IOUtils.copy(inputStream, outputStream);
inputStream.close();
}
outputStream.close();<br/>
or you can also use SAXParser

Categories