So I am using the following code to write to a file in Java, the text prints fine, but it has strange characters between the letters.
public static void foo() throws IOException{
static RandomAccessFile configFile;
configFile.writeChars("#Minecraft server properties");
configFile.close();
}
I was searching for answer and everything pointed to incorrect usage of writeUTF() so I decided to try that instead which semi-fixed the issue, but I still have that character at the beginning of the line.
public static void foo() throws IOException{
static RandomAccessFile configFile;
configFile.writeUTF("#Minecraft server properties");
configFile.close();
}
My questions are: what is that char? Vim shows it as an # and what can I do to remove it?
That char is related with the encoding of the file you are creating.
Try using the following code instead:
public static void createConfigFile() throws IOException {
FileWriter writer = new FileWriter("PATH_TO_YOUR_CONFIG_FILE", false);
writer.append("#Minecraft server properties");
// Append any other content you need here.
writer.flush();
writer.close();
}
Hope that helps!
Related
This question already has answers here:
Java FileWriter with append mode
(4 answers)
Closed 6 years ago.
I would like to write in a single file in java but in different methods. I wrote this
import java.io.*;
public class Test {
public static File file = new File("text.log");
public static void main (String [] args) throws IOException
{
FileWriter input= new FileWriter(file);
input.write("hello");
input.write("\n");
input.close();
test();
}
public static void test() throws IOException
{
FileWriter input= new FileWriter(file);
input.write("world");
input.write("\n");
input.close();
}
}
The output is just world. It looks like calling the function test() overwrites what was previously written.
You need to open the FileWriter in append mode by passing true as the second argument:
public static File file = new File("text.log", true);
From the Javadoc:
public FileWriter(String fileName, boolean append)
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.
When you write new FileWriter(file, true), it will append instead of overwrite.
I'm very confused...
public class Testing {
public static void main(String[] args) throws FileNotFoundException, IOException, InterruptedException {
System.out.println("Testing overwrite");
FileWriter writer = new FileWriter("c:\\testing\\testfile.txt", false);
writer.write("First test");
writer.flush();
TimeUnit.SECONDS.sleep(5);
writer.write("Second test");
writer.flush();
writer.close();
}
}
After completion, the contents of the file is:
First testSecond test
The boolean passed to the FileWriter with the value of False should be causing an overwrite, not an append, according to the Java docs here: Java 6 Filewriter API
I've had this problem in the past, and I've used a RandomAccessFile to bypass the problem, but now it's just annoying me!
Any ideas or suggestions would be greatly appreciated, thanks!
When calling
FileWriter writer = new FileWriter("c:\\testing\\testfile.txt", false); it will overwrite the file. It won't overwrite per .write. The option only applies for the contructor.
I need to physically print out my output box (using a printer) for a class.
Can someone please explain to me how to do this?
Instead of printing the console from eclipse, you can output all your System.out.println() directly to a file. Basically, you are using the file as a debugger instead of the console window. To do this, you can use the code below.
import java.io.*;
PrintWriter writer = new PrintWriter("debuggerOutput.txt", "UTF-8");
//in your class constructor, you will need to add some exception throws
write.println("I used to be in the debugger, but now I go in the file!!")
For each System.out.println(), add an extra write.println() with the same thing in the parenthesis so it outputs to the file what goes in the console.
Then, you will see all your output in a file that you can easily print.
At the end, make sure to write.close()
Full code:
import java.io.*;
public class test {
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter writer = new PrintWriter("myFile.txt", "UTF-8");
writer.println("The line");
writer.close();
}
}
I'm making a game in Java, but can't figure out how to get information from a text file so that I can load the game. I have the saved files set up so that on every line there is the name of a method in my Main program. What I need to do is to look in a certain line for text and execute the method that the text is referring to.
This should do it. Obviously you'll need to handle exceptions:
public class FileReaderTest
{
public static void main(String[] args) throws IOException, IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException
{
final FileReaderTest object = new FileReaderTest();
final BufferedReader reader = new BufferedReader(new FileReader(new File("/path/to/file")));
for (String line = reader.readLine(); line != null; line = reader.readLine())
{
object.getClass().getMethod(line).invoke(object);
}
}
}
Now, this is assuming that you are talking about a .txt file.
I/O is the basic Idea, If you master that, then you are set. I stands for input, and O, for Output.
Now, you need to make an variable equal to inputStream.readInt();
EDIT:
But for more help, you can also go with reading
Reading a text file in java
Hope this helps!
I want to write the numbers to a file. The programs runs without any errors but when I open the file that I wrote to, the contents of the file is something like "!"#$%&'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ".
I cross-checked by reading the contents of the file using FileInputStream and printing the contents. The IDE prints the desired output but the integers in the file are not stored in readable form.
Can anyone tell me why the integers are not populating in the file as intended?
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException{
try{
FileOutputStream fos = new FileOutputStream("Exercise_19.txt");
for(int i = 0;i<=200; i++){
fos.write((int)i);
}
fos.close();
}
catch(IOException ex){
ex.printStackTrace();
}
}
Quite why you're getting that data in the file, I'm not sure, but the FileOutputStream is for writing raw bytes of data rather than human readable text. Trying using a FileWriter instead.
fos.write(int) writes a byte using the lowest 8-bits of the integer.
if you want to write text to a file, a simpler option is to use PrintWriter (note PrintWriter can use FileOutputStream so it can be done, but you really have to know what you are doing.)
public static void main(String... args) throws FileNotFoundException {
PrintWriter pw = new PrintWriter("Exercise_19.txt");
for (int i = 0; i <= 200; i++)
pw.println(i);
pw.close();
}
FileOutputStream Class's Write() method will write the data in Byte format. so you can not read it in normal Notepad format. However you can read it using FileInputStream Class.
Syntax for Writing is as follows, look at this link
write(int b)
Writes the specified byte to this file output stream.
A Complete Writing and Reading Example you can find here.