Text file: Adding a line of text only once? - java

Within my application I am adding the functionality that allows me to save details to a txt file.
It is working fine, however I am trying to add a header to the txt file just once at the top of the file.
The problem I am getting is that it is being generated on every second line, not just once.
How can I change the method below to sort this problem?
Note: header is a string declared earlier in the activity.
Write to File method:
public void writeToFileEEGPower(String data){
boolean isHeader=true;
Time t= new Time();
t.setToNow();
int timeFileMinute= t.minute;
int timeFileDate= t.yearDay;
int timeFileYear= t.year;
//creating file name
String fileName= "Maths-" +timeFileMinute + timeFileDate + timeFileYear + android.os.Build.SERIAL;
//creating the file where the contents will be written to
File file= new File(dir, fileName + ".txt");
FileOutputStream os;
try{
boolean append= true;
os= new FileOutputStream(file, append);
String writeMe =data + "\n";
if(isHeader){
os.write(header.getBytes());
isHeader=false;
}
os.write(writeMe.getBytes());
os.close();
} catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
particular code section of interest:
if(isHeader){
os.write(header.getBytes());
isHeader=false;
}

public void writeToFileEEGPower(String data, boolean isHeader){
....
}
Pass in "true" for header and pass in "false" for anything after the first one?

I was able to solve the problem by doing as was suggested in the comments and other answer.
Basically I declared the boolean: isHeader=true;within the onCreate() method of the Activity and removed it's declaration from the writeToFileEEGPower() method.

Related

Replace specific expressions in file Java

I want to copy a annotated file, and replace those annotations in the new copy. However I am struggling on how to do the replacing. I am currently reading the whole file into a string and replacing the annotations before saving the string to a new file:
String file = null;
void openAnnotatedSource(String path){
byte[] encoded = null;
try {
encoded = Files.readAllBytes(Paths.get(anotatedpath + "/" + path));
} catch(Exception e) {
System.out.println("Error opening annotated source.");
}
file = new String(encoded, StandardCharsets.UTF_8);
}
void replaceAnotation(String anotation, String config){
file = file.replace(anotation, config);
}
void replaceAnotation(String anotation, int config){
file = file.replace(anotation, String.valueOf(config));
}
void createFinalSource(String path){
try{
Files.write(Paths.get(targetpath + "/" + path), file.getBytes());
} catch(Exception e) {
System.out.println("Couldnt create " + targetpath + "/" + path);
}
}
I don't know if I'm doing this correctly because having the file the whole time as a string does not seem correct to me.
Any decent text editor has a search&replace facility that supports regular expressions.
If however, you have reason to reinvent the wheel in Java, the approach you followed is a decent way, you are writing the modified contents into a different new file, so reading the contents from source file into a string and modifying the contents of string and creating a new file with updated string does not cause any problems.

Java IO Create / Append File

Im trying to create a file if it doesnt exist, if it does exist append to it.
Is this the best way to do it? Im not sure having two try catches inside one method is good personally?
public static void main(String [] args)
{
String fileLocation = "/temp/";
String name = "Bob";
String timeStamp = "1988-03-15";
Path path = Paths.get(fileLocation+ "info.log");
if(!Files.exists(path)){
try {
Files.createFile(path);
} catch (IOException e) {
e.printStackTrace();
}
}
try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
SimpleDateFormat tTimeFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
writer.write(tTimeFormatter.format(System.currentTimeMillis()) + " name: " + name + " Timestamp: "+ timeStamp);
writer.newLine();
} catch (IOException e) {
System.out.print(e.getStackTrace());
}
}
You can write to file with StandardOpenOptions: CREATE and APPEND.
Files.write(Paths.get(""), new byte[] {}, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
CREATE - means if file doesn't exists it creates new one otherwise get existing.
APPEND - means append new data to existing content in file.
So, you can do all your operations with a single line.
The File.createNewFile() method creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. This methods return a true value if the file is created successfully and false if the file already exists or the operation failed.
if (myFile.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
Try using the printWriter class like this
java.io.PrintWriter p = new java.io.PrintWriter(yourFileHere);
// You can use println to print a new line if it allready exists
p.println(yourTextHere);
// Or append to the end of the file
p.append("TEXT HERE!!!!")

Writing to an External File on Android --- File Doesn't Register, But Java Can Read

I'm trying to write to an external txt (or csv) file for Android. I can run an app, close it, and run it again, and readData() will read back to my log what I've stored. However, the dirFile (file directory) appears nowhere within my Android files (even if I connect it to a computer and search).
Something interesting, though: if I clear my log (similar to a list of print statements shown within Eclipse) and disconnect my phone from my computer, then reconnect it, the log reappears with everything I've ever written to my file (even if I later overwrote it)...yet the app isn't even running!
Here is my code. Please help me understand why I cannot find my file!
(Note: I've tried appending a "myFile.txt" extension to the directory, but it just causes an EISDIR exception.)
public void writeData(String dirName){
try
{
File root = new File(getExternalFilesDir(null), dirName);
// Writes to file
//
// The "true" argument allows the file to be appended. Without this argument (just root),
// the file will be overwritten (even though we later call append) rather than appended to.
FileWriter writer = new FileWriter(root, true);
writer.append("Append This Text\n");
writer.flush();
writer.close();
// Checks if we actually wrote to file by reading it back in (appears in Log)
//readData(dirName);
}
catch(Exception e)
{
Log.v("2222", "2222 ERROR: " + e.getMessage());
}
}
If you're interested, here's the function I wrote to read in the data:
public void readData(String dirName){
try
{
File root = new File(getExternalFilesDir(null), dirName);
// Checks to see if we are actually writing to file by reading in the file
BufferedReader reader = new BufferedReader(new FileReader(root));
try {
String s = reader.readLine();
while (s != null) {
Log.v("2222", "2222 READ: " + s);
s = reader.readLine();
}
}
catch(Exception e) {
Log.v("2222", "2222 ERROR: " + e.getMessage());
}
finally {
reader.close();
}
}
catch(Exception e) {
Log.v("2222", "2222 ERROR: " + e.getMessage());
}
}
Thanks!
even if I connect it to a computer and search
if I clear my log (similar to a list of print statements shown within Eclipse) and disconnect my phone from my computer, then reconnect it, the log reappears with everything I've ever written to my file (even if I later overwrote it).
What you are seeing on your computer is what is indexed by MediaStore, and possibly a subset of those, depending upon whether your computer caches information it gets from the device in terms of "directory" contents.
To help ensure that MediaStore indexes your file promptly:
Use a FileOutputStream (optionally wrapped in an OutputStreamWriter), not a FileWriter
Call flush(), getFD().sync(), and close() on the FileOutputStream, instead of calling flush() and close() on the FileWriter (sync() will ensure the bytes are written to disk before continuing)
Use MediaScannerConnection and scanFile() to tell MediaStore to index your file
You can then use whatever sort of "reload" or "refresh" or whatever option is in your desktop OS's file manager, and your file should show up.
This blog post has more on all of this.
public void create(){
folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES),"video");
boolean success = true;
if (!folder.exists()) {
success=folder.mkdirs();
}
if (success) {
readfile();
} else {
System.out.println("failed");
}
}
The above code will be used to crete the directory in th emobile at desired path
private void readfile() {
// TODO Auto-generated method stub
AssetManager assetManager = getResources().getAssets();
String[] files = null;
try {
files = assetManager.list("clipart");
} catch (Exception e) {
Log.e("read clipart ERROR", e.toString());
e.printStackTrace();
}
for(String filename : files) {
System.out.println("File name => "+filename);
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("clipart/" + filename);
out = new FileOutputStream(folder + "/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("copy clipart ERROR", e.toString());
e.printStackTrace();
}
}}private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}}
this is my code used to write file in internal memory from the assets folder in project. This code can read all type(extension) of file from asset folder to mobile.
Don't forget to add permission in manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and call the above function by
readfile();//this call the function to read and write the file
I hope this may help you.
Thank you.

Filewriter issues - Java Android

My filewriter does not seem to create a file. This is my code:
public void peopledetails_write(ArrayList<PeopleDetails> peopledetails_file) {
////numbers is the arraylist of numbers.
///names is the arraylist of names of people.
///Written to file like 01235 678 908, Daniel; 01245 645 123, Bob Marley; etc.
///Like a CSV file.
try{
FileWriter writer_file = new FileWriter("PeopleDetailsFile");
String filestring = ""; ///initializes filestring, which is written to the file.
for(PeopleDetails person : peopledetails_file){
String person_detail_string = "";
person_detail_string = person.name + "," + person.number;
filestring = filestring + person_detail_string + ";";
}
writer_file.write(filestring);
writer_file.close();
}
catch (IOException e) {
Log.e("ERROR", e.toString());
}finally{
///Hopefully won't get an error here.
Intent switch_menu = new Intent(this, MenuList.class);
startActivity(switch_menu);
}
}
It acts on the finally, and takes the user back to the main menu of my app. I have managed to debug the section where this code is, and reckon that this is faulty code, as I get a FileNotFound exception, after this section should have written a file.
What is wrong with this code?
here where your going wrong, unless api points to some specific directory, you should always
use absolute file path(complete file path).
FileWriter writer_file = new FileWriter(complete_file_path);

How to save the data into File in java?

I have one problem, that is I have one string of data and I want to save it into a separate file every time. Please give me a suggestion.
Thanks,
vara kumar.pjd
Use a timestamp in the filename so you can be sure it is unique. Below example uses a timestamp in milliseconds which should be enough in most cases.
If you expect you can have multiple files within 1 millisecond then you could do something with a GUID/UUID. Note that GUID/UUID could result in duplicates too, however this chance is extremely rare.
import java.io.*;
class FileWrite
{
public static void main(String args[])
{
try{
// Create file
FileWriter fstream = new FileWriter(System.currentTimeMillis() + "out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
You don't need to compute the filename by yourself, have a look at File.createTempFile.
From the javadoc:
Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. If this method returns successfully then it is guaranteed that:
The file denoted by the returned abstract pathname did not exist before this method was invoked, and
Neither this method nor any of its variants will return the same abstract pathname again in the current invocation of the virtual machine.
This method provides only part of a temporary-file facility. To arrange for a file created by this method to be deleted automatically, use the deleteOnExit() method.
A one liner. Using base 36 for the ids will make the file names shorter.
IOUtils.write(text, new FileWriter(Long.toString(System.currentTimeMillis(), 36)+".txt")));
http://commons.apache.org/io/
One solution can be, use a random number generator to generate a random number. Use this random number with some text as a filename. Maintain a list of already used names and each time you are saving the file, check through this list if the file name is unique.
One of possible ways to get File object with unique name could be:
public static File getUniqueFile(String base, String ext, int index) {
File f = new File(String.format("%s-%03d.%s", base, index, ext));
return f.exists() ? getUniqueFile(base, ext, index + 1) : f;
}
Update: and here goes basic usage/test case:
String s = "foo string\n";
FileWriter writer = null;
for (int i = 0; i < 10; i++) {
File f = getUniqueFile("out", "txt", 0);
try {
writer = new FileWriter(f);
writer.write(s);
writer.close();
writer = null;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
if (writer != null) { try { writer.close(); } catch (Exception e) {} }

Categories

Resources