Generating Code into an existing file with Java - java

I am trying to write a code that will generate code into an already existing HTML File. It seems like I can not reach the existing HTML file in my repository.
I would be happy if someone could help.
Here is the method that should do the code generation:
public static void generate() {
PrintWriter pWriter = null;
try {
pWriter = new PrintWriter(new BufferedWriter(new FileWriter("<filename>.html"))); //and path
pWriter.println("<code we want to put in>");
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (pWriter != null){
pWriter.flush();
pWriter.close();
}
}
}

Check your file read and write access. If you use Mac-OS or linux try to execute chmod 666 .html
If you use Java SE 7+, you can use try-with-resources with PrintWriter.
Check the path to your file.
Try this code below:
public static void generate() {
try (PrintWriter pWriter = new PrintWriter(new File("test.html"))){
pWriter.println("<CODE>");
pWriter.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}

Related

Writing to file in java - close or flush

I'm writing a logger to my java program (in csv format) with bufferedWriter and FileWriter.
When i open the csv file while the program is running and continues writing to the file, I got this exception: "The process cannot access the file because it is being used by another process".
What i want is when i open the csv file while the program is running, The csv file will open in read mode and the program will writing successfully to the file.
I solved it by changing the closing of bufferedWriter and FileWriter to .flush() instead of .close()
Original minimal logger code (with the original close function)
public class logger {
private BufferedWriter bw = null;
private FileWriter fw = null;
private File file = null;
logger(String nclass) {
path = "c:\\test\\test.csv";
this.file = new File(path);
// Check if the file is already exist.
if (!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
}
public void writeToFile(String msg) {
entryWrite();
try {
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
fw.append(msg);
} catch (IOException e) {
e.printStackTrace();
} finally {
close();
exitWrite();
}
}
}
private void close() {
try {
if (bw != null) {
bw.close();
bw = null;
}
if (fw != null) {
fw.close();
fw = null;
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
My solution function
private void close() {
try {
if (bw != null) {
bw.flush();
bw = null;
}
if (fw != null) {
fw.flush();
fw = null;
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
Now my answer is if it is ok not to close the stream and just use with flush?
Can there be any problems later? Because in all my tests its run well.
Thanks !!
Would it be ok some honesty?, in a very humble way. Sorry but stinky code:
why setting to null "bw" and "fw"?, globals?, why?
"ex.printStackTrace();" ? really?, no log4j or alike?
why not using a finally block?, what happens if an exception occurs while reading writing the file?
Someone has already answered this, for code refer to this excellent answer:
Is it necessary to close a FileWriter, provided it is written through a BufferedWriter?
Just do bufferedWriter object close.
bw.close();
say, you have a large file.txt.
Now u are gonna take something from a file and make a new smaller text file each time.
in that case,
somehow you have to write some lines of code to determine when you finish writing on a particular file. Then use flag to write bw.close();
eventually, you have to initialize the second file and do your task. then bw.close();
if you don't write fw.close(), then the file will be empty.
so, make sure each file writing operation you have to write bw.close()

File not found exception even after bufferedwriter close

New edit:
Now i found the cause, it is because there are two servers and it write into temp folder in 1st server and try to read from the 2nd one. But I still didn't find a solution for this unless write to Amazon S3 and read from there.
I tried to export csv with struts2 action. However if I tried to export 10 times i can only succeed once, all the others failed with File not found exception (if I refresh the link again, the file can be downloaded). Here is my code:
public String exportFile(String fileName) {
File exportFile = null;
try {
if (CollectionUtils.isEmpty(receipts)) {
return "";
}
exportFile = File.createTempFile(fileName, ".csv");
exportFile.deleteOnExit();
try (BufferedWriter fw = new BufferedWriter(new FileWriter(exportFile))) {
try {
fw.write("test");
} finally {
fw.close();
}
}
return exportFile.getPath();
} catch (Exception ex) {
logger.error("Error exporting report. ", ex.getMessage());
}
return "";
}
String getStreamFromPath(String filePath) {
try {
File downloadFile = new File(filePath);
fileInputStream = new FileInputStream(downloadFile);
return SUCCESS;
} catch (IOException e) {
log.error(e.getMessage(), e);
return ERROR;
}
}
This is really weird, when i test in another server it works totally fine. Any ideas?

How can I load an xml resource file from within an executible Jar file and save it to the folder the jar is located in?

I have a custom java server. It uses an external xml config file.
I have some command line options to help the user, the usual stuff for showing a help file, setting ports, etc...
I've recently added a command to generate a default config file for the server. It's an xml file. After researching my options, packing a default xml file in the jar seemed to be the way to go, but I'm obviously missing something.
So far my code looks like this:
public class ResourceLoader {
private File outFile = null;
private Reader fileReader = null;
private Writer fileWriter = null;
private InputStream is = null;
private char[] buffer = null;
public ResourceLoader() {
outFile = new File("default-server.xml");
}
public void generateDefaultServerXml() {
is = ResourceLoader.class.getResourceAsStream("/default-server.xml");
if (is == null) {
System.out.println("Configuraiton File generation failed. The InputStream is null.");
} else {
fileReader = new InputStreamReader(is);
}
buffer = new char[4096];
FileOutputStream fos;
try {
fos = new FileOutputStream(outFile);
fileWriter = new OutputStreamWriter(fos);
while (fileReader.read(buffer) != -1) {
fileWriter.write(buffer, 0, buffer.length);
fileWriter.flush();
buffer = new char[4096];
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fileReader.close();
fileWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The code above works perfectly fine when I run it in eclipse, but intitially, after I export the jar file the server could not locate the default-server.xml file when I run the command from the terminal.
The file itself is located in a package called main.resources along with some other config files and the above class.
I have since moved the ResourceLoader.class to another package. After doing that the server seems to find the xml file in the main.resources package (InputStream is not null) but the resulting generated default-server.xml file is empty.
Again, this all works perfectly well when I run it in eclipse, it's only after I export the project and try issue the command from the terminal that the process fails. What am I doing wrong?
The above class is instantiated, and the generateDefaultServerXml() is called, from the main method of the server.
EDIT: My path for writing default-server.xml was slightly wrong. Now that I've adjusted it the code works exactly as expected when I run it in Eclipse. The resource is read in the correct way, and written to the file in the correct location. But it still doesn't work when I try the same thing from the jar file.
You current line ResourceLoader.class.getResourceAsStream("/default-server.xml") means that you are trying to load a resource named default-server.xml from the root of your classpath, or put simpler, from the root of your jar file. This means that xml file should NOT be in any package inside the jar file.
When you assemble your jar file and then run jar tf my.jar on it, do you see your default-server.xml file? Does it reside in some package or in the root of the jar file?
The problem here is since you are packaging the application as a jar. The procedure to call an external resource is quite different.
You need to have a folder structure as
root
--your jar
--your xml file
Your code shallwork if the application is using an default-server.xml file inside the jar.
Otherwise, Replace below line in your code if you want to use an external default xml file.
is = new FileInputStream("./default-server.xml");
If the output file you want at root location the use below code
public ResourceLoader() {
outFile = new File("./default-server.xml");
}
Alternate code as per discussion
public class ResourceLoader {
public void generateDefaultServerXml() {
try {
String defaultxmltext =readFileToString("/default-server.xml");
writeFileFromInputString(defaultxmltext);
} catch (IOException e) {
//exception
}
}
public static void writeFileFromInputString(String everything) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("./default-server.xml"))) {
everything = everything.replaceAll("\n", System.getProperty("line.separator"));
writer.write(everything);
}
}
public static String readFileToString(String path) throws IOException {
String everything = null;
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
everything = sb.toString();
}
return everything;
}
}
Hope this helps
consider your file located on src/main/resources try this
getClass().getClassLoader().getResource(fileName)
well as far as i can see your main problem is that you are passing the wrong path, since you mentioned the xml is under main.resources you will need to add this to the path when trying to load the file, here is a sample piece of code that should work for you
Scanner sc = null;
PrintWriter writer = null;
try {
sc = new Scanner(getClass().getResourceAsStream("main/resources/server.xml"));
writer = new PrintWriter("./default_server.xml", "UTF-8");
while(sc.hasNextLine()) {
writer.println(sc.nextLine());
}
} catch (Exception e) {
} finally {
if(sc != null) {
sc.close();
}
if(writer != null){
writer.close();
}
}

Is .txt extension necessary in File() constructor?

Like in the method i have attached i have used practiceData.txt i am getting same results while using just practiceData in file constructor so is it ok to use file without any extension or txt is better?
private void saveData(String data) {
File file = new File(this.getFilesDir(), "practiceData.txt");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(data.getBytes());
saveStatus = "Data was successfully saved.";
} catch (java.io.IOException e) {
e.printStackTrace();
saveStatus = "Error occurred: " + e.toString();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
It doesn't matter what file extension you use, it just tells the OS how to open the file. So yes, you can use no extension and it will work just as well.
If you intend the file to be opened manually via another application, it may be helpful to use a standard extension however.

How to open (as in launch) text file in Java?

My program has the following code where output is a StringBuilder:
try
{
BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"));
bw.write(output.toString());
}
catch(IOException e)
{
System.out.println("File error: "+e.getMessage());
}
after the bw.write(output.toString()); I want to have another line that launches the textfile with the default application. I considered using the desktop API but heard it has bad cross-platform compatibility. Any suggestions?
File file = new File("somefile.txt");
Desktop desktop = Desktop.getDesktop();
desktop.open(file);
I think you were looking for this.
public static void main(String[] args) {
try {
Main m = new Main();
} catch (IOException e) {
e.printStackTrace();
}
}
public Main() throws IOException {
File file = new File("test.txt");
if (!file.exists())
file.createNewFile();
Desktop.getDesktop().edit(file);
}
Worked for me

Categories

Resources