Replace specific expressions in file Java - 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.

Related

Javafx save textField to a text file

I have this code for saving to a text file however, I can't seem to find a way to make it save to not the user.home folder but to another folder on my hard drive. I searched in many places but couldn't really find anything that could help me.
It works with the user.home setting but if I try to change it, it doesn't. The program, when executed, comes up with Source not found.
saveBtn.setOnAction(new EventHandler<ActionEvent>()
{
public void handle(ActionEvent event)
{
Object source = event.getSource();
String s = null;
//Variable to display text read from file
if (_clickMeMode) {
FileOutputStream out = null;
try {
//Code to write to file
String text = titleField.getText();
byte b[] = text.getBytes();
String outputFileName = System.getProperty("user.home"
+ File.separatorChar+"home")
+ File.separatorChar + "Movies2.txt";
out = new FileOutputStream(outputFileName);
out.write(b);
out.close();
//Clear text field
titleField.setText("");
}catch (java.io.IOException e) {
System.out.println("Cannotss text.txt");
} finally {
try {
out.close();
} catch (java.io.IOException e) {
System.out.println("Cannote");
}
}
}
else
{
//Save text to file
_clickMeMode = true;
}
window.setTitle("Main Screen");
window.setScene(mainScreen);
}
});
Your file name is incorrectly assigned:
String outputFileName = System.getProperty("user.home"
+ File.separatorChar+"home")
+ File.separatorChar + "Movies2.txt";
You are passing a string of the form "user.home/home" to System.getProperty().
Since there is no such property, this will return null.
Then you concatenate this with /Movies2.txt, so outputFileName will be something like null/Movies2.txt.
(A simple System.out.println(outputFileName) will confirm this.)
Instead of building the filename by hand like this, you should use a higher-level API to do it. E.g.:
Path outputFile = Paths.get(System.getProperty("user.home"), "home", "Movies2.txt");
OutputStream out = Files.newOutputStream(outputFile);
out.write(b);
If you also need (or might need) to create the directory, you can do
Path outputDir = Paths.get(System.getProperty("user.home"), "home");
Files.createDirectories(outputDir);
Path outputFile = outputDir.resolve("Movies2.txt");
OutputStream out = Files.newOutputStream(outputFile);
out.write(b);

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!!!!")

Filer always throws FilerException

Edit: I just found out that not a IOExcpetion but a FilerException is thrown. Therefore I changed that in the description and the title.
I'm working with Annotation Processing to generate some files for my java project. Now I always get an FilerException when the Annotation Processing tries to generate my files.
This is the way I create the files (GenClass and GenAnnotation are custom classes that abstract the generated classes. They weren't changed in about half a year so I'm sure the error isn't somewhere there. The way I write the files also didn't change in the last year.):
public static boolean generateJavaSourceFile(final ProcessingEnvironment processingEnv,
final GenClass element, final String fileName, final Class<?> generatorClass) {
boolean succeed = false;
Writer fw = null;
Filer f = processingEnv.getFiler();
// Mark the class as generated
GenAnnotation generatedAnnotation = getAnnotation(generatorClass);
element.pushImport(generatedAnnotation);
element.addAnnotation(generatedAnnotation);
try {
JavaFileObject jfo = f.createSourceFile(fileName, (Element[]) null);
// create new java source file
fw = jfo.openWriter();
// write the GenClass object into file
fw.write(element.toString());
succeed = true;
} catch (FilerException e) {
LOGGER.severe("Couldn't generate file (" + fileName + ")!");
processingEnv.getMessager().printMessage(Kind.ERROR,
"Could not create source file " + fileName
+ " because it already exists");
throw new RuntimeException(e.getMessage(), e);
} catch (IOException e) {
LOGGER.severe("Couldn't generate file (" + fileName + ")!");
throw new RuntimeException(e.getMessage(), e);
} finally {
if (fw != null) {
try {
fw.close(); // flush and close the stream
} catch (IOException e) {
LOGGER.severe("Couldn't close file [" + fileName + "]!");
}
}
}
LOGGER.fine(fileName + " written");
return succeed;
This is the message of the exception:
Source file already created: /path/to/the/file/to/create
I did change something on my processors, however the error only occurs for a certain type of files (Filters we use to filter data) and I didn't change anything on the processor that generates the filters. I added a new processor that works with a different annotation and those file are generated correctly.
Does anyone know what the cause of this error could be?
I had an error in another processor (that had nothing to do with the processor that generates the Filters) and that caused this error. Now that I fixed that error also this behavior stopped. I'm not really sure why this FilerException happened all the time, however it is gone now.

Text file: Adding a line of text only once?

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.

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);

Categories

Resources