How to choose RandomAccessFile dynamically? - java

I had written a program using RandomAccessFile class to read binary data. The code is as follows
RandomAccessFile in = new RandomAccessFile('BOT.GRD', "r");
in.read(a);
Now I want to choose file dynamically rather than providing directly as above. I tried a lot and I was unable to do that. Can any one help me on this?

Offer the user a JFileChooser to select the File. See How to Use File Choosers
for more details & examples.

Assign the filename to a variable and pass that into the RandomAccessFile constructor:
String filename = "somedynamicname.grd";
RandomAccessFile file = new RandomAcessFile(filename, "r");
file.read(a);

Related

How to user Scanner check if a Zip file compressed by CSV or other type of files in JAVA?

I am trying to use Scanner read ZipInputStream line by line, below is the code i have
ZipInputStream inputStream = new ZipInputStream(bodyPartEntity.getInputStream());
inputStream.getNextEntry();
Scanner sc = new Scanner(inputStream);
while (sc.hasNextLine()) {
log.info(sc.nextLine());
}
and it works fine.
But I have a question, what if a user compressed an image or different type of files (not CSV) as a Zip. Is there a way that I can check that so I can throw an exception for it? Also, is there a way to read next file?
For now, if I compressed multiple files, I'm only able to read one. And then sc.hasNextLine() will be equal to false.
Anyway, I can read the next file?
you should loop over your zip file like this:
ZipEntry entry;
while((entry = inputStream.getNextEntry())!=null){
// do your logic here...
// for example: entry.getName()
}
For the file type, you could use something like this, inside of while loop:
MimetypesFileTypeMap mtft = new MimetypesFileTypeMap();
String mimeType = mtft.getContentType(entry.getName());
System.out.println(entry.getName()+" type: "+ mimeType);
Happy coding!
First, you need to loop over your zip, as it was suggested before.
Then you need to check the type of the file with Apache Tika. I think this is the best library if you need to determine the type of the file. It can detect filetype from file extension and file content as well. To use file content is the safest solution, and it fits best for your scenario (stream).
See more info here:
description of Tika detector interface
API
example, how to use it

Is using the File class in Java how you create a file?

I need some serious help with concepts. I have been given background context on the class, specifically this:
I just need to understand the purpose of this class? Can I create a text file (or any other type of file) with its constructors? Is this just for handling files, if so, what does that mean?
Any help whatsoever will be greatly appreciated!
Thank you
You could use the java.io.File to create a file on the file system:
File myFile = new File("myFile.txt");
myFile.createNewFile();
Note that invoking the constructor won't create the file on the file system. To create an empty file, the createNewFile() method has to be invoked.
The File simply represents a abstraction of the file location, not the file itself. It comes with operations on the file identified by the path: exists(), delete(), length(), etc.
What you probably want is to use the classes that allow you to write content to a file:
If you are to write text, you should use the Writer interface.
If you are to write binary content, you should use the OutputStream interface.
The classes FileWriter and FileOutputStream are, respectively, the ones that link the File and Writer/OutputStream concepts together. Those classes create the file on the file-system for you.
FileWriter myFileWriter = null;
File myFile = new File("myFile.txt");
try {
// file is created on the file-system here
myFileWriter = new FileWriter(myFile);
myFileWriter.write("hello");
} finally {
if (myFileWriter != null) {
myFileWriter.close();
}
}
You can create a file using the File.createNewFile method, or, if you are using Java 7 or newer, using the newer Files.createFile method.
The difference between the old File and the new Path classes is that the former mixed a reference to a path to a file on the filsystem and operations you can do on it, and the latter is just representing the path itself but allows you to query it and analyze its structure.

Being able to read a .dat in English, and then being able to edit the file

File file = new File(directory + player.getUsername() + ".dat");
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream outFile = new FileOutputStream(file);
DataOutputStream write = new DataOutputStream(outFile);
write.writeUTF(player.getUsername());
write.writeUTF(player.getPassword());
write.writeInt(player.getStaffRights());
write.writeInt(player.getPosition().getX());
write.writeInt(player.getPosition().getY());
write.writeInt(player.getPosition().getZ());
write.writeInt(player.getGender());
Ok so pretty much what this code above does is it makes new character files for this game im working with. But the problem im having is that the character information that this code is putting into a .dat I cant read when I try and open in lets say notepad its just gibberish. I need to be able to open these .dats and be able to read/edit the text in english. Any help?
When you save data with a DataOutputStream, it will be saved in Java's native binary serialization format, not as plain text which you can read with for example Notepad.
If you want to write plain text to a file, use one of the subclasses of java.io.Writer to write to the file instead of DataOutputStream - for example PrintWriter.
PrintWriter out = new PrintWriter(file);
out.println(player.getUsername());
// etc...
// Also, don't forget to close when you are done
out.close();
Have the player object implement Serilizable and as long as all of its properties are serilizable as well, such as strings and ints, the serialization will be done.
Refer to the serialization tutorial:
Tutorial

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.

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