Method to read XML file and parse it - java

How to read an XML file saved in the local folder and then use the stream object to parse it?

You can use a FileInputStream (see docs).
File file = new File("C:\\Temp\\myxml.xml");
InputStream stream = new FileInputStream(file)

If you need an URL, you can use file.toURI().toURL() or use a File-URL: file://C:/Temp/myxml.xml
Otherwise, directly go with the FileInputStream as suggest by Jeff.

Related

FileItem inputStream to FileInputStream

I have a web page with an upload feature which lets you upload a excel file, on hitting upload an Ajax call is fired. From there I get the FileItem input stream and using the method fileItem.getInputStream(), I have another class with a method which I need to pass the file to, which has a FileInputStream parameter. So my question is how do I convert the input stream to a FileInputStream?
A detailed solution would be appreciated as I am a junior developer, so I am still learning.
Many thanks.
From JavaDoc
A FileInputStream obtains input bytes from a file in a file system.
I would suggest two solutions:
The proper one is to change the API and to have InputStream as a parameter. I don't see a reason why you have FileInputStream in your API.
If you don't own the API and cannot change it I'm afraid you will need to save the InputStream to temp file and then create FileInputStream giving a path to this file (it's a suboptimal solution as you first write the file to disk - risking out of space - and then read it and streaming API is designed for reading / writing data on the fly)
If you are using org.apache.commons.fileupload.FileItem interface then your class is probably DefaultFileItem which is a subclass of DiskFileItem. So you can cast FileItem to DiskFileItem. then if you look at the source code of DiskFileItem you'll find that getInputStream() is actually returning a FileInputStream or a ByteArrayInputStream If you get a FileInputStream from DiskFileItem you can pass it directly to your other class. But if you get a ByteArrayInputStream you will have to write the contents to your own temporary file and then open another FileInputStream on this temp file. There is also another method DiskFileItem.getStoreLocation() which seem to return the server side File used for upload, but it may return null if the file is cached in memory.
In conclusion: you cannot be sure that there is going to be a server side file because the upload may be cached in memory. Therefore if you need a FileInputStream elsewhere you will have to create it yourself by creating a temp file. There is an example on how to pipe between two streams here.
//Pass file path/name directly to FileInputStream
FileInputStream input1 = new FileInputStream("input.txt");
//Save file path that has been passed in by the user, into a string variable.
String fileName = args[0];
//pass path to File object
File inputFile = new File(fileName);
//pass file object to FileOutputStream
FileOutputStream output = new FileOutputStream(inputFile);

Need to convert AssetInputStream to FileInputStream

I have implemented a data structure which is working on my computer and now I am trying to port it into my android application. I open a raw .dat resource and get a InputStream but I need to get a FileInputStream:
FileInputStream fip = (FileInputStream) context.getResources().openRawResource(fileID);
FileChannel fc = fip.getChannel();
long bytesSizeOfFileChannel = fc.size();
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0L, bytesSizeOfFileChannel);
...
The code above throws the following exception since an InputStream can not be cast to a FileInputStream but that's just what I need:
java.lang.ClassCastException: android.content.res.AssetManager$AssetInputStream cannot be cast to java.io.FileInputStream
All my code is build on using this FileChannel with a FileInputStream so I want to keep using it. Is there a way to go from having an InputStream from context.getResources().openRawResource(fileID) and then convert it into a FileChannel?
Somewhat relevant posts in which I could not find a working solution for my case which android:
How to convert InputStream to FileInputStream
Converting inputStream to FileInputStream?
Using FileChannel to write any InputStream?
A resource isn't a file. Ergo it can't be used as a memory-mapped file. If you have resources that are so enormous they need to be memory-mapped, they probably shouldn't be resources at all. And if they are small, memory mapping brings no advantages.
This might be late, but i think you can indirectly get a FileInputStream from an InputStream. what i suggest is this: get the input stream from resource, then create a temp file,get a FileOutputStream from it. read the InputStream and copy it to FileOutputStream.
now the temp file has the contents of your resource file, and now you can create a FileInputStream from this file.
I don't know if this particular solution is useful to you, but i think it can be used in other situations.
As an example, if your file is in the assets folder, you get an InputStream and then a FileInputStream using this method:
InputStream is=getAssets().open("video.3gp");
File tempfile=File.createTempFile("tempfile",".3gp",getDir("filez",0));
FileOutputStream os=newFileOutputStream(tempfile);
byte[] buffer=newbyte[16000];
int length=0;
while((length=is.read(buffer))!=-1){
os.write(buffer,0,length);
}
FileInputStream fis=new FileInputStream(tempfile);

What is equivalent of fopen_s() in java?

I want to convert this code in java
fopen_s(&stream, "path", "w+");
w+ opens empty file with both reading and writing. If the given file exists, it's contents are destroyed.
any suggestions?
It seems 1.7 java is required for the nio, so my take is
RandomAccessFile f = new RandomAccessFile(name, "rw");
f.setLength(0);
I am not a Java programmer, but I had a short hunt around the web and it seems Java has a RandomAccessFile and you open it with the mode "rw".
The true equivalent is to use Files.newByteChannel.
final SeekableByteChannel channel = Files.newByteChannel(Paths.get("path"),
StandardOpenOptions.READ, StandardOpenOptions.WRITE,
StandardOpenOptions.TRUNCATE_EXISTING);
The READ and WRITE options determine if the file should be opened for reading and/or writing.
...
TRUNCATE_EXISTING - If this option is present then the existing file is truncated to a size of 0 bytes. This option is ignored when the file is opened only for reading.
Looks like you want either FileOutputStream or FileWriter, depending on what kind of data you want to write. Either of them can be instantiated with a filename.
FileOutputStream fis = new FileOutputStream("/path/to/file");
FileWriter fw = new FileWriter("/path/to/file2");
And both will clobber the file if it already exists. (Though constructors exists for appending instead of over-writing)
Quick way to achieve what you want:
import java.io.*;
// Create a new file output connected to "myfile.txt"
out = new FileOutputStream("myfile.txt");
// Create a new file input connected to "myfile.txt"
in = new FileInputStream("myfile.txt");
You might want to take a look at the java.io package at the official docs, especially the RandomAccessFile Class and also this quick guide.

Java: use URL object for File object

I want to read some data for my app. Here my code:
URL url = Myclass.class.getResource("/data/file.txt"); //Myclass is my class name
File file = new File(url.toString()); //maybe I met error here.
//File Constructor just receive String object, I don't know how to convert
FileInputStream reader = new FileIputStream(file);
I don't know how to change url to File to read it. Please tell me how to solve.
Thanks :)
You can't read a resource as if it were a file. The following syntax should work:
InputStream resource = MyClass.class.getResourceAsStream("/data/file.txt");
To avoid relative / absolute path issues, you can also use:
InputStream resource = MyClass.class.getClassLoader().getResourceAsStream("/data/file.txt");

Is this the best way to rewrite the content of a file in Java?

I want to rewrite the contents of a file.
What I have thought of so far is this:
Save the file name
Delete the existing file
Create a new empty file with the same name
Write the desired content to the empty file
Is this the best way? Or is there a more direct way, that is, not having to delete and create files, but simply change the content?
To overwrite file foo.log with FileOutputStream:
File myFoo = new File("foo.log");
FileOutputStream fooStream = new FileOutputStream(myFoo, false); // true to append
// false to overwrite.
byte[] myBytes = "New Contents\n".getBytes();
fooStream.write(myBytes);
fooStream.close();
or with FileWriter :
File myFoo = new File("foo.log");
FileWriter fooWriter = new FileWriter(myFoo, false); // true to append
// false to overwrite.
fooWriter.write("New Contents\n");
fooWriter.close();
I would highly recommend using the Apache Common's FileUtil for this. I have found this package invaluable. It's easy to use and equally important it's easy to read/understand when you go back a while later.
//Create some files here
File sourceFile = new File("pathToYourFile");
File fileToCopy = new File("copyPath");
//Sample content
org.apache.commons.io.FileUtils.writeStringToFile(sourceFile, "Sample content");
//Now copy from source to copy, the delete source.
org.apache.commons.io.FileUtils.copyFile(sourceFile, fileToCopy);
org.apache.commons.io.FileUtils.deleteQuietly(sourceFile);
More information can be found at:
http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html
See: java.io.RandomAccessFile
You'll want to open a File read-write, so:
RandomAccessFile raf = new RandomAccessFile("filename.txt", "rw");
String tmp;
while (tmp = raf.readLine() != null) {
// Store String data
}
// do some string conversion
raf.seek(0);
raf.writeChars("newString");
Unless you're just adding content at the end, it's reasonable to do it that way. If you are appending, try FileWriter with the append constructor.
A slightly better order would be:
Generate new file name (e.g. foo.txt.new)
Write updated content to new file.
Do atomic rename from foo.txt.new to foo.txt
Unfortunately, renameTo is not guaranteed to do atomic rename.
Since Java 7 and the new file API this is really simple using the java.nio.file.Files class:
Files.write(Path.of("foo.log"), "content".getBytes(StandardCharsets.UTF_8));
New in Java 8 to write list of UTF-8 string:
Files.write(Path.of("foo.log"), List.of("content line 1", "content line 2"));
New in Java 11 to write UTF-8 string:
Files.writeString(Path.of("foo.log"), "content");
In the below example, the "false" causes the file to be overwritten, true would cause the opposite.
File file=new File("C:\Path\to\file.txt");
DataOutputStream outstream= new DataOutputStream(new FileOutputStream(file,false));
String body = "new content";
outstream.write(body.getBytes());
outstream.close();
There are times when one may want to keep a huge empty file so as to avoid extra cost of the OS allocating space on need basis. This is generally done by databases, Virtual machines and also in batch programs that process and write bulk data. This would improve the performance of the application significantly. In these cases, writing a new file and renaming it would not really help. Instead, the empty file will have to be filled up. That is when one must go for the override mode.
Guava Files.write "Overwrites a file with the contents of a byte array":
Files.write(bytes, new File(path));

Categories