The code I've written is supposed to overwrite over the contents of the selected text file, but it's appending it. What am I doing wrong exactly?
File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;
try {
f2 = new FileWriter(fnew,false);
f2.write(source);
/*for (int i=0; i<source.length();i++)
{
if(source.charAt(i)=='\n')
f2.append(System.getProperty("line.separator"));
f2.append(source.charAt(i));
}*/
f2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EDIT
I tried making a new temp.txt file and writing the new contents into that, deleting this text file and renaming temp.txt to this one. Thing is, the deletion is always unsuccessful. I don't think I have to change user permissions for this do I?
Also, a part of my program lists all the files in this directory, so I'm guessing they're being used by the program and so can't be deleted. But why not overwritten?
SOLVED
My biggest "D'oh" moment! I've been compiling it on Eclipse rather than cmd which was where I was executing it. So my newly compiled classes went to the bin folder and the compiled class file via command prompt remained the same in my src folder. I recompiled with my new code and it works like a charm.
File fold=new File("../playlist/"+existingPlaylist.getText()+".txt");
fold.delete();
File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
try {
FileWriter f2 = new FileWriter(fnew, false);
f2.write(source);
f2.close();
} catch (IOException e) {
e.printStackTrace();
}
Your code works fine for me. It replaced the text in the file as expected and didn't append.
If you wanted to append, you set the second parameter in
new FileWriter(fnew,false);
to true;
SOLVED
My biggest "D'oh" moment! I've been compiling it on Eclipse rather than cmd which was where I was executing it. So my newly compiled classes went to the bin folder and the compiled class file via command prompt remained the same in my src folder. I recompiled with my new code and it works like a charm.
File fold = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fold.delete();
File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");
String source = textArea.getText();
System.out.println(source);
try {
FileWriter f2 = new FileWriter(fnew, false);
f2.write(source);
f2.close();
} catch (IOException e) {
e.printStackTrace();
}
Add one more line after initializing file object
File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fnew.createNewFile();
This simplifies it a bit and it behaves as you want it.
FileWriter f = new FileWriter("../playlist/"+existingPlaylist.getText()+".txt");
try {
f.write(source);
...
} catch(...) {
} finally {
//close it here
}
The easiest way to overwrite a text file is to use a public static field.
this will overwrite the file every time because your only using false the
first time through.`
public static boolean appendFile;
Use it to allow only one time through the write sequence for the append field
of the write code to be false.
// use your field before processing the write code
appendFile = False;
File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;
try {
//change this line to read this
// f2 = new FileWriter(fnew,false);
// to read this
f2 = new FileWriter(fnew,appendFile); // important part
f2.write(source);
// change field back to true so the rest of the new data will
// append to the new file.
appendFile = true;
f2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Related
When I use my program within Eclipse everything works flawlessly, the JSON file is saved between launches. The problem occurs when i export the project to a Runnable Jar File, the saving of the JSON file no longer works, at all. I can still read from the file, but it doesn't save it.
Here is the "writing/saving" code I've written.
/*
* Write to character JSON file
*/
public void saveCharacterInfo() {
JSONObject obj = JSONUtils.getJSONObjectFromFile("/character.json");
obj.put("day", c.getDay());
obj.put("name", c.getCharName());
obj.put("hp", c.getCharHp());
obj.put("maxHp", c.getCharHpMax());
obj.put("armor", c.getCharArmor());
obj.put("speed", c.getCharSpeed());
obj.put("strength", c.getCharStrength());
obj.put("money", c.getCharMoney());
obj.put("food", c.getCharFood());
obj.put("maxFood", c.getCharMaxFood());
obj.put("morale", c.getCharMorale());
obj.put("bait", c.getCharBait());
try {
URL resourceUrl = getClass().getResource("/character.json");
File file = new File(resourceUrl.toURI());
FileWriter writer = new FileWriter(file);
writer.write(obj.toString());
writer.flush();
writer.close();
} catch (Exception e) {
}
}
Since outside Eclipse neither the bin nor the file itself haven't been created yet, you have to create it, at first and if there was a file before, since we want to overwrite it, we use the delete method before creating it. So the whole changes are written here:
public void saveCharacterInfo() {
JSONObject obj = JSONUtils.getJSONObjectFromFile("/character.json");
obj.put("day", c.getDay());
obj.put("name", c.getCharName());
obj.put("hp", c.getCharHp());
obj.put("maxHp", c.getCharHpMax());
obj.put("armor", c.getCharArmor());
obj.put("speed", c.getCharSpeed());
obj.put("strength", c.getCharStrength());
obj.put("money", c.getCharMoney());
obj.put("food", c.getCharFood());
obj.put("maxFood", c.getCharMaxFood());
obj.put("morale", c.getCharMorale());
obj.put("bait", c.getCharBait());
try {
URL resourceUrl = getClass().getResource("/character.json");
File file = new File(resourceUrl.toURI());
file.getParentFile().mkdirs();
file.delete();
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(obj.toString());
writer.flush();
writer.close();
} catch (Exception e) {
}
}
I tested it and the way to make the jar to create new folders is to execute it from the windows command console with:
java -jar jarName.jar
Or to create a bat file on the same folder.
I am attempting to display PDFs to the user in their browser using a web service. Once they pass in the URL containing the variables needed. My program first downloads the PDF to local storage then proceeds to copy it to the stream and displays it. Once the viewer is able to view the PDF we wish to delete the file locally so that we do not wind up storing every file searched for. I have managed to accomplish most of this task however I am having issues deleting the file once it is displayed to the user.
Even when I attempt to manually delete the file I receive the "Currently in use in the Java SE Binary" message
Code below:
File testFile = new File("C:\\Users\\stebela\\workspace\\my-app\\invoice"+invNum+".pdf");
try
{
ServletOutputStream os = res.raw().getOutputStream();
FileInputStream inputStr = new FileInputStream(testFile);
IOUtils.copy(inputStr, os);
os.close();
inputStr.close();
//finished settings
res.status(200);
testFile.delete();
} catch (IOException e)
{
System.out.println(e.getMessage());
}
If you don't write to the file, you'r code should work.
If you call inputStr.close(); the file is no longer used by java and it can be deleted.
Pleace check, if your file is not used by any other programm. It's the best if you reboot your PC.
If it still not works, it would be interessting to know, what res is and if your file get's sendet.
I've read this part of the documentation and i think this should solve your problem.
It reads the file into a String and change the header for png images. As the http Body it uses the String of the file.
Make sure, if you change the response type, you have to change the line res.type("image/png"); to the new one.
Here you find the most common ones
File testFile = null;
try {
testFile = new File("C:\\Users\\stebela\\workspace\\my-app\\invoice"+invNum+".png");
FileInputStream fin = new FileInputStream(testFile);
int charAsInt = 0;
String httpBody = "";
while((charAsInt = fin.read()) != -1){
httpBody +=(char)charAsInt;
}
fin.close();
res.body(httpBody);
res.type("image/png");
res.status(200);
testFile.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In my current project I am having an issue with not receiving a file not found exception. My driver file passes the path to be opened to the constructor that is building a library of books. I am using JFileChooser to get the path. In trying to force an error (entering the name of a file that does not exist), it builds the library with no information in it, and does not throw an error.
Driver Code:
//open an existing library
JFileChooser dlg = new JFileChooser ("LibraryData");
FileNameExtensionFilter filter = new FileNameExtensionFilter ("Text Files", "txt");
dlg.setFileFilter(filter);
dlg.setDialogTitle("Select Existing File");
dlg.setApproveButtonToolTipText("Select the file you want to open and click me.");
int button = dlg.showOpenDialog(null);
if (button == dlg.APPROVE_OPTION)
{
currentPath = dlg.getSelectedFile().getPath();
library = new PersonalLibrary(currentPath);
System.out.println("===========================================================");
System.out.println("File opened successfully from: \n" + currentPath);
System.out.println("===========================================================");
}
Util.enterToContinue();
Util.clearScreen();
break;
Library Code:
public PersonalLibrary(String path)
{
try
{
File myFile = new File(path);
if (myFile.exists())
{
Scanner input = new Scanner(myFile);
while(input.hasNext())
{
//code that populates the library
}
input.close();
saveNeeded = false;
}
}
catch (FileNotFoundException e)
{
System.out.println("Error: " + e.getMessage());
}
Your checking if the file exists the catch block will never be executed.
if(myFile.exists())
If it doesn't exist nothing else will be executed including catch block. FileNotFoundException could not occur in this block of code. If you want to catch FileNotFoundException get rid of the if block. Or just add an else block and do you processing there whatever processing you want to do when a file doesn't exist.
the method File#exists() checks if a file is existing or not. If it does, it returns true and goes into your if block.
Since the file is not there, it just simply skips the if block and moves on. Since no attempt was made to access a non-existing file object, the exception is not thrown.
If you would like to throw an exception, you have to do so yourself like this,
if(file.exists()) {
//do file operation
} else {
throw new FileNotFoundException("Oops! No file...");
}
I have a java application running into a weblogic server.
The application have to write a file into the path \bla\john doe (for example).
For this, I used the java.io.File library to:
1. Verify if the path exists
2. If not, create it.
3. Verify if the file exists
4. if not, create it
5. Write the bytes into the file.
The correct behavior would be to create the directory bla into the root of the weblogic's current domain and then create a john doe inside it.
The problem is: in my current enviroment it works like a charm, but in the client's one, the application does not consider the backslash as an element of the path, and instead of creating two directories, the application only creates one, literally named as \bla\john does.
So, instead of:
-domain_root
-bla
-john does
I get the following:
-domain_root
-\bla\john does
(and if I escape it, occurres the same but with two backslash)
The odd is that if I use the commom slash (/bla/john doe), it works..
-domain_root
-bla
-john does
Does any one knows what possibly can be happening?
script for check the path
public File checkPath(String path) {
File f = new File(cls_Util.NeutralizeFilePath(path));
if (!(f.exists() && f.isDirectory())) {
try {
f.mkdirs();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return f;
}
script for check the file:
public File checkFile(String path){
File f = new File(path);
return checkFile(f);
}
public File checkFile(File f) {
if (!(f.exists() && f.isFile())) {
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return f;
}
script for create file
public File writeFile(String path, byte[] binaryfile) {
File file = checkFile(path);
if (file != null) {
FileOutputStream fos;
try {
fos = new FileOutputStream(path);
try {
fos.write(binaryfile);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return file;
}
return null;
}
And to create the file:
String filePathPub = pathPub + newName;
File FilePathPub = writeFile(filePathPub, p_Arquivo);
On Windows the \ starts an absolute path; on Unix/Linux the backslash is a valid filename character (and therefore starts a relative path).
I would suggest you try to avoid using file name concatenation platform specific separators if you are not familiar with the semantic:
File current = new File();
File bla = new File(current, "bla");
(or simply stick to / (forward slash as used by Unix) to separate path components). Java translates this to the Windows character automatically).
First of all I am iMacros scripts writer.
This is java function for writing a file (not fully complete but you will get the idea)
bufferedWriter = new BufferedWriter(new FileWriter(filename));
//Start writing to the output stream
bufferedWriter.write("Writing line one to file");
Now bellow is java function used in JavaScript to do the same task as the function above and I run that .js file in iMacros. Works like a charm.
//Function to write the file
function writeFile(filename, data)
{
try
{
//write the data
out = new java.io.BufferedWriter(new java.io.FileWriter(filename, true));
out.newLine();
out.write(data);
out.close();
out=null;
}
catch(e) //catch and report any errors
{
alert(""+e);
}
}
Now I need a java function that will create file and folder on Hard Drive location and I found this.
package com.mkyong.file;
import java.io.File;
import java.io.IOException;
public class CreateFileExample
{
public static void main( String[] args )
{
try {
File file = new File("c:\\newfile.txt");
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
But now I need java function that will create folder and an empty file (with different extensions like .txt .csv etc.) and the function will work in JavaScript.
Can anyone give me some guide lines from the two examples above? How can I write a functions in Java and run it in JavaScript?
I won't claim to fully understand the question, but this is how to make sure some directory exists, and to create a random file in it:
// make the dir and ensure the entire path exists
File destinationDir = new File("c:\\whereever\you\want\that\file\to\land").mkdirs();
// make some file in that directory
File file = new File(destinationDir,"whateverfilename.whateverextension");
// continue with your code
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
This function is used in iMacros .js file. It is a Java method called in JavaScript.
createFile("C:\\testingfolder","test.csv");
function createFile(folder,file)
{
destinationDir = new java.io.File(folder).mkdirs();
file = new java.io.File(folder,file);
file.createNewFile();
}
The function creates folder and in it creates a file.