I have the following Java code which will search in an xml for a specific tag and then will add some text to it and save that file. I couldnt find a way to rename the emporary file to the original file. Please suggest.
import java.io.*;
class ModifyXML {
public void readMyFile(String inputLine) throws Exception
{
String record = "";
File outFile = new File("tempFile.tmp");
FileInputStream fis = new FileInputStream("InfectiousDisease.xml");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
FileOutputStream fos = new FileOutputStream(outFile);
PrintWriter out = new PrintWriter(fos);
while ( (record=br.readLine()) != null )
{
if(record.endsWith("<add-info>"))
{
out.println(" "+"<add-info>");
out.println(" "+inputLine);
}
else
{
out.println(record);
}
}
out.flush();
out.close();
br.close();
//Also we need to delete the original file
//outFile.renameTo(InfectiousDisease.xml);//Not working
}
public static void main (String[] args) {
try
{
ModifyXML f = new ModifyXML();
f.readMyFile("This is infectious disease data");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Thanks
First delete the original file and then rename the new file:
File inputFile = new File("InfectiousDisease.xml");
File outFile = new File("tempFile.tmp");
if(inputFile.delete()){
outFile.renameTo(inputFile);
}
A good method to rename files is.
File file = new File("path-here");
file.renameTo(new File("new path here"));
In your code there are several issues.
First your description mentions renameing the original file and adding some text to it. Your code doesn't do that, it opens two files, one for reading and one for writing (with the additional text). That is the right way to do things, as adding text in-place is not really feasible using the techniques you are using.
The second issue is that you are opening a temporary file. Temporary files remove themselves upon closing, so all the work you did adding your text disappears as soon as you close the file.
The third issue is that you are modifying XML files as plain text. This sometimes works as XML files are a subset of plain text files, but there is no indication that you attempted to ensure that the output file was an XML file. Perhaps you know more about your input files than is mentioned, but if you want this to work correctly for 100% of the input cases, you probably want to create a SAX writer that writes out all a SAX reader reads, with the additional information in the correct tag location.
You can use
outFile.renameTo(new File(newFileName));
You have to ensure these files are not open at the time.
Related
I'm creating an app which requires to write a file for every user (in JSON format).
The app successfully creates the file, But it's empty. In the code I added a finer output to see how the converted JSON String looks like, and I noticed that it's complete (it contains everything, so the conversion is ok). But the string isn't present in the file.
//create a new FileWriter C:/.../42.guser
FileWriter writer = null;
//for every User
for(int i=0; i<users.size(); i++) {
try {
File f = new File(Users.usersDir.getPath()+"/"+i+".guser");
//Create new file
f.createNewFile();
writer = new FileWriter(f);
//convert to json and write to file. Here we get the object with KEY = keys[i].
String stringedUsr = gson.toJson(users.get(keys[i]));
logger.finer("Converted user: \""+stringedUsr+"\""); //Output seems ok
//Write (NOT WORKING)
writer.write(stringedUsr);
logger.fine("Wrote updated user \""+keys[i]+"\" to file "+f.getCanonicalPath());
} catch (IOException e) {
FAILS++;
e.printStackTrace();
}
}
//End of for
What am I doing wrong?
Note: i gave to the app all the necessary Permissions. No AccessControlExceptions
First of all think about closing your writer.
When closing, it should flush() your data first (as mentioned in the doc here)
You can also flush() manually.
I don't understand how to use TextIO's readFile(String Filename)
Can someone please explain how can I read an external file?
public static void readFile(String fileName) {
if (fileName == null) // Go back to reading standard input
readStandardInput();
else {
BufferedReader newin;
try {
newin = new BufferedReader( new FileReader(fileName) );
}
catch (Exception e) {
throw new IllegalArgumentException("Can't open file \"" + fileName + "\" for input.\n"
+ "(Error :" + e + ")");
}
if (! readingStandardInput) { // close current input stream
try {
in.close();
}
catch (Exception e) {
}
}
emptyBuffer(); // Added November 2007
in = newin;
readingStandardInput = false;
inputErrorCount = 0;
inputFileName = fileName;
}
}
I had to use TextIO for a school assignment and I got stuck on it too. The problem I had was that using the Scanner class I could just pass the name of the file as long as the file was in the same folder as my class.
Scanner fileScanner = new Scanner("data.txt");
That works fine. But with TextIO, this won't work;
TextIO.readfile("data.txt"); // can't find file
You have to include the path to the file like this;
TextIo.readfile("src/package/data.txt");
Not sure if there is a way to get it to work like the Scanner class or not, but this is what I've been doing in my course at school.
The above answer (about using the correct file name) is correct, however, as a clarification, make sure that you actually use the proper file path. The file path suggested above, i.e. src/package/ will not work in all circumstances. While this will be obvious to some, for those of you who need clarification, keep reading.
For example (and I use NetBeans), if you have already moved the file into NetBeans, and the file is already in the folder you want it to be in, then right click on the folder itself, and click 'properties'. Then expand the 'file path' section by clicking on the three dots next to the hidden file path. You will see the actual file path in its entirety.
For example, if the entire file path is:
C:\Users..\NetBeansProjects\IceCream\src\icecream\icecream.dat
Then, in the java code file itself, you can write:
TextIo.readfile("src/icecream/icecream.dat");
In other words, make sure you include the words 'src' but also everything that follows the src as well. If it's in the same folder as the rest of the files, you won't need anything prior to the 'src'.
I have a code for 1 doc file only .I need to convert multiple doc file in folder into respective textfile.
Code for Single doc file Into text file:
import java.io.*;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
public class ReadDocFile {
public static void main(String[] args) {
File file = null;
try {
// Read the Doc/DOCx file
file = new File("document");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
XWPFDocument doc = new XWPFDocument(fis);
XWPFWordExtractor ex = new XWPFWordExtractor(doc);
String text = ex.getText();
//write the text in txt file
File fil = new File("D:\\wordtotextoutput\\java1new.txt");
Writer output = new BufferedWriter(new FileWriter(fil));
output.write(text);
output.close();
} catch (Exception exep) {
}
}
}
I will just give you the logic. you should be able to convert it to java
First the input docs files should land into a particular folder.
Scan the folder and get the No. of files in the folder.
Put a for loop and fetch the file one by one. Put all your code logic here inside the loop.
check the file type of the fetched file. if its .doc/.docx process it.
Process all the files in the similar way.
Later delete the processed file.
From Package org.apache.commons.io.FileUtils
You can use
FileUtils.copyDirectory(srcDir, destDir);
and then delete the old file if you want to.
I have tried creating a file, using the code below:
import java.io.File;
public class DeleteEvidence {
public static void main(String[] args) {
File evidence = new File("cookedBooks.txt");
However, the file cookedBooks.txt does not exist anywhere on my computer. I'm pretty new to this, so I'm having problems understanding other threads about similar problems.
You have successfully created an instance of the class File, which is very different from creating actual files in your hard drive.
Instances of the File class are used to refer to files on the disk. You can use them to many things, for instance:
check if files or directories exist;
create/delete/rename files or directories; and
open "streams" to write data into the files.
To create a file in your hard disk and write some data to it, you could use, for instance, FileOutputStream.
public class AnExample {
public static void main(String... args) throws Throwable {
final File file = new File("file.dat");
try (FileOutputStream fos = new FileOutputStream(file);
DataOutputStream out = new DataOutputStream(fos)) {
out.writeInt(42);
}
}
}
Here, fos in an instance of FileOutputStream, which is an OutputStream that writes all bytes written to it to an underlying file on disk.
Then, I create an instance of DataOutputStream around that FileOutputStream: this way, we can write more complex data types than bytes and byte arrays (which is your only possibility using the FileOutputStream directly).
Finally, four bytes of data are written to the file: the four bytes representing the integer 42. Note that, if you open this file on a text editor, you will see garbage, since the code above did not write the characters '4' and '2'.
Another possibility would have been to use an OutputStreamWriter, which would give you an instance of Writer that can be used to write text (non-binary) files:
public class AnExample {
public static void main(String... args) throws Throwable {
final File file = new File("file.txt");
try (FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter out = new OutputStreamWriter(fos, StandardCharsets.UTF_8)) {
out.write("You can read this with a text editor.");
}
}
}
Here, you can open the file file.txt on a text editor and read the message written to it.
File evidence = new File(path);
evidence.mkdirs();
evidence.createNewFile();
File is an abstract concept of a file which does not have to exist. Simply creating a File object does not actually create a physical object.
You can do this in (at least) two ways.
Write something to the file (reference by the abstract File object)
Calling File#createNewFile
You can also create temporary files using File#createTempFile but I don't think this is what you are trying to achieve.
You have only created an object which can represent a file. This is just in memory though. If you want to access the file you must us ea FileInputStream or a FileOutputStream. Then it will also be created on the drive (in case of the outputstream).
FileOutputStream fo = new FileOutputStream(new File(oFileName));
fo.write("test".getBytes());
fo.close();
This is just ur creating file object by using this object u need to call one method i.e createFile() method..
So use evidence.createNewFile(); if you are creating just file.
else if u want to create file in any specific location then specify your file name
i.e File evidence=new File("path");
In this case if ur specifying any directoty
String path="abc.txt";
File file = new File(path);
if (file.createNewFile()) {
System.out.println("File is created");
}
else {
System.out.println("File is already created");
}
FileWriter fw = new FileWriter(file, true);
string ab="Hello";
fw.write(ab);
fw.write(summary);
fw.close();
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.)