Is there a more elegant way to do the following?
try (FileWriter myWriter = new FileWriter(Paths.get(folder,fileName).toAbsolutePath().toString())){
I have folder path and filename as string and I want to safely combine them. For example if
String folder = "/tmp/"
String fileName = "/myfile.txt"
to not end up with
"/tmp//myfile.txt"
or with
String folder = "/tmp"
String fileName = "myfile.txt"
to not end up with
"/tmpmyfile.txt"
The way I am using is transforming String to path and back to String which feels weird, but it looks like FileWriter does not accept Path directly.
Is there some more elegant solution than the one I have?
Use Files.newBufferedWriter(Path, OpenOption...).
try (Writer myWriter = Files.newBufferedWriter(Paths.get(folder, fileName))) {
// other code
}
Note that, while the FileWriter constructor uses the JVM's default encoding, this method uses the UTF-8 encoding, which is considered generally more useful. If you need to replicate the behavior of the FileWriter constructor, use
Files.newBufferedWriter(path, Charset.defaultCharset());
Related
code that should read html file and write the result another file the buffered writer writes the file but when the code is run with different urlit doesn't appends but rewrites the file and the previous content disappears
the solution recuired is that when jsoup iterates new html the result should add to output file and not rewrite
changed different writer types other than buffered writer
public class WriteFile
{
public static void main(String args[]) throws IOException
{
String url = "http://www.someurl.com/registers";
Document doc = Jsoup.connect(url).get();
Elements es = doc.getElementsByClass("a_code");
for (Element clas : es)
{
System.out.println(clas.text());
BufferedWriter writer = new BufferedWriter(new FileWriter("D://Author.html"));
writer.append(clas.text());
writer.close();
}
}
}
Don't mistake the append-method of the BufferedWriter as appending content to the file. It actually appends to the given writer.
To actually append additional content to the file you need to specify that when opening the file writer. FileWriter has an additional constructor parameter allowing to specify that:
new FileWriter("D://Author.html", /* append = */ true)
You may even be interested in the Java Files API instead, so you can spare instantating your own BufferedWriter, etc.:
Files.write(Paths.get("D://Author.html"), clas.text().getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
Your loop and what you are writing may further be simplifiable to something as follows (you may then even omit the APPEND-open option again, if that makes sense):
Files.write(Paths.get("D://Author.html"),
String.join("" /* or new line? */,
doc.getElementsByClass("a_code")
.eachText()
).getBytes(),
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
What I want to achieve is to create a file regardless of whether the file exists or not.
I tried using File.createNewFile() but that will only create the file if it does not already exists. Should I use File.delete() and then File.createNewFile()?
Or is there a clearer way of doing it?
FileWriter has a constructor that takes 2 parameters too: The file name and a boolean. The boolean indicates whether to append or overwrite an existing file. Here are two Java FileWriter examples showing that:
Writer fileWriter = new FileWriter("c:\\data\\output.txt", true); //appends to file
Writer fileWriter = new FileWriter("c:\\data\\output.txt", false); //overwrites file
You can use a suitable Writer:
BufferedWriter br = new BufferedWriter(new FileWriter(new File("abc.txt")));
br.write("some text");
It will create a file abc.txt if it doesn't exist. If it does, it will overwrite the file.
You can also open the file in append mode by using another constructor of FileWriter:
BufferedWriter br = new BufferedWriter(new FileWriter(new File("abc.txt"), true));
br.write("some text");
The documentation for above constructor says:
Constructs a FileWriter object given a File object. If the second
argument is true, then bytes will be written to the end of the file
rather than the beginning.
Calling File#createNewFile is safe, assuming the path is valid and you have write permissions on it. If a file already exists with that name, it will just return false:
File f = new File("myfile.txt");
if (f.createNewFile()) {
// If there wasn't a file there beforehand, there is one now.
} else {
// If there was, no harm, no foul
}
// And now you can use it.
When I create a csv file through java then for name "Men's Commemorative ® ELITE Bib Short", it is storing "Men's Commemorative ® ELITE Bib Short" in csv. So I have to remove "Â" from csv file through java file.
public boolean writeProductsToFile()
{
final List<ProductModel> products = getListrakDao().getProducts();
final String filePath = getFilePath() + getProductFileName();
final File file = new File(filePath);
FileWriter writer = null;
writer = new FileWriter(file);
for (final ProductModel productModel : products)
{
productData.append(StringEscapeUtils.unescapeHtml("\"" + productModel.getName() + "\""));
productData.append(getFieldSeparator());
writer.write(productData.toString());
}
}
This is my code...where "baseProduct.getName()" is fetching name of product.
In database product name is "Men's Commemorative ® ELITE Bib Short". But in csv it is getting written as "Men's Commemorative ® ELITE Bib Short". So how can I remove characters like "Â". So tha#t name in csv should be like exactly in database.
To a degree, this is a shot in the dark, but...
As a general practice, try to be explicit with the character sets you use.
Instead of
FileWriter writer = null;
writer = new FileWriter(file);
write
final Charset utf8 = java.nio.charset.StandardCharsets.UTF_8;
final Writer writer = new OutputStreamWriter(new FileOutputStream(file), utf8);
(imports left out for brevity, StandardCharsets requires Java 7 or later)
This allows actively controlling the used charset when writing. If not set, the system uses the default charset, which may not be appropriate. If UTF-8 is not what you desire, try something else, like ISO_8859_1.
When you read your CSV file, make sure the reader/editor you use supports the used charset and uses it. Otherwise, you'll see strange characters, much like you did.
i want to add data inside of an existing json file..
this is my code:
JsonWriterWithGui(){
if(ae.getSource() == btn_submit){
String lname = (String)lbl_name.getText().toString();
String ladd = (String)lbl_add.getText().toString();
String lcontact = (String)lbl_contact.getText().toString();
FileWriter jsonFileWriter = new FileWriter( "E:\\"+tsave+".json");
jsonFileWriter.write(jsonObject.toJSONString());
jsonFileWriter.flush();
jsonFileWriter.close();
this code is already working. but I am trying to update a json file that already exists.
This is a bit of a guess because the problem you're having isn't entirely clear from the question, but if you're finding that your writes are overwriting instead of appending then try changing this line:
FileWriter jsonFileWriter = new FileWriter( "E:\\"+tsave+".json");
...to this:
FileWriter jsonFileWriter = new FileWriter("E:\\"+tsave+".json", true);
You see, FileWriter is backed by FileOutputStream, which takes a boolean argument saying whether new content should be appended or not. This boolean is false by default so if you want to append then you need to explicitly say so.
I am trying to create a back up file for an html file on a web server.
I want the backup to be in the same location as the existing file (it's a quick fix). I want to create the file using File file = new File(PathName);
public void backUpOldPage(String oldContent) throws IOException{
// this.uri is a class variable with the path of the file to be backed up
String fileName = new File(this.uri).getName();
String pathName = new File(this.uri).getPath();
System.out.println(pathName);
String bckPath = pathName+"\\"+bckName;
FileOutputStream fout;
try
{
// Open an output stream
fout = new FileOutputStream (bckFile);
fout.close();
}
// Catches any error conditions
catch (IOException e)
{
System.err.println ("Unable to write to file");
System.exit(-1);
}
}
But if instead I was to set bckPath like this, it will work.
String bckPath = "C://dev/server/tomcat6/webapps/sample-site/index_sdjf---sd.html";
I am working on Windows, not sure if that makes a difference.
The result of String bckPath = pathName+"\"+bckName;
is bckPath = C:\dev\server\tomcat6\webapps\sample-site\filename.html - this doesn't result in a new file.
Use File.pathSeparator, that way you dont need to worry what OS you are using.
Try to use File.getCanonicalPath() instead of plain getPath(). This helps if the orginal path is not fully specified.
Regarding slashes, / or \ or File.pathSeparator is not causing the problem, because they are all the same on Windows and Java. (And you do not define bckFile in your code, only bckPath. Also use getCanonicalPath() on the new created bckPath.)