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.
Related
I'm working with the FileOutputStream class in java, but I don't know how to delete "the contents" of a file (the main reason i need overwrite the file).
If you want to delete the contents of the file, but not the file itself, you could do:
PrintWriter pw = new PrintWriter("file.txt");
pw.close();
A few seconds of Googling got me this:
how to delete the content of text file without deleting itself
How to clear a text file without deleting it?
To delete the file completely, do:
File file = new File("file.txt");
f.delete();
Call File.delete() which deletes the file or directory denoted by this abstract pathname.
File f = new File("foo.txt");
if (f.delete()) {
System.out.println("file deleted");
}
The main reason i need overwrite the file ...
One way to do this is to delete the file using File.delete() or Files.delete(Path). The latter is preferable, since it can tell you why the deletion fails.
The other way is to simply open the file for writing. Provided that you don't open in "append" mode, opening a file to write will truncate the file to zero bytes.
Note that there is a subtle difference in the behavior of these two approaches. If you delete a file and then create a new one, any other application that has the same file open won't notice. By contrast, if you truncate the file, then other applications with the file open will observe the effects of the truncation when they read.
Actually, this is platform dependent. On some platforms, a Java application that tries to open a file for reading that another file has open for writing will get an exception.
Yes, you can do it with FileOutputStream. All the answers given say about PrintWriter but the same can be done with FileOutputStream. The int representation of space is 32. So simply pass the file to the instance of FileOutputStream as:
FileOutputStream out = new FileOutputStream(file);
out.write(32);
This will clear the contents of the file. Surely use this only of u want to do it with FileOutputStream only otherwise use PrintWriter.
I am working on a project which creates a file with .bat extension.
In C++ it is possible by using
fstream myfile ("example.bat");
fstream<<"echo \"hello\" ";
But how can I do it in Java (JDK 8)?
I would suggest reading up on Java File IO. Whatever you want to call the file you're saving, you can. There aren't any custom extensions as opposed to normal extensions.
Additional Resource
I think this code does what you want. createFile will throw FileAlreadyExistsException if specified file already exists.
Path myBat = Paths.get("example.bat");
Files.createFile(myBat);
try( BufferedWriter reader = Files.newBufferedWriter(myBat) ) {
reader.append("hello");
}
Edit:
I think try-with-resources is needed here.
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
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);
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));