Creating and writing to a file with UTF-8 encoding - java

Here is my Java code.
File file = new File(path);
StringWriter sw = new StringWriter();
//Do something.
out.println(sw.toString()); //Works fine; prints.
try {
FileUtils.writeStringToFile(file, sw.toString(), "UTF-8");
} catch (IOException e) {
throw new RuntimeException( e );
}
I don't already have the file created, and neither is it creating it after the execution.
How can I do this?

See File.createNewFile().
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. ..
As mentioned by #JohnWatts in comments:
..both PrintWriter and your code create the file, but pre-1.3 FileUtils.writeStringToFile does not.

Don't use StringWriter, use PrintWriter instead:
PrintWriter w = new PrintWriter(file);
w.print(string);
w.flush();
w.close()

I checked the code and it works.
The only problem that I could think of is path value. Try with hardcoded path value. Because I doubt file is getting created and you are not able to find it.

Related

How to force content from a file to be utf-8 in java spring?

I have a function that creates a file, but when I check the created file, its contents are not in utf-8, which causes problems with the contents in latin languages.
I thought that indicating the media type as html would be enough to keep formatting, but it did not work.
File file = new File("name of file");
try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) {
writer.write(contents);
writer.flush();
writer.close();
MultipartFile multipartFileToSend = new MockMultipartFile("file", "name of file", MediaType.TEXT_HTML_VALUE, Files.readAllBytes(Paths.get(file.getPath())));
} catch (IOException e) {
e.printStackTrace();
}
I'd like to know how to force this, because so far I have not figured out how.
Any tips?
Instead of using FileWriter, create a FileOutputStream. You can then wrap this in an OutputStreamWriter, which allows you to pass an encoding in the constructor. Then you can write your data to that inside a try-with-resources Statement:
try (OutputStreamWriter writer =
new OutputStreamWriter(new FileOutputStream("your_file_name"), StandardCharsets.UTF_8))
// do stuff
}

Java - How to Clear a text file without deleting it?

I am wondering what the best way to clear a file is. I know that java automatically creates a file with
f = new Formatter("jibberish.txt");
s = new Scanner("jibberish.txt");
if none already exists. But what if one exists and I want to clear it every time I run the program? That is what I am wondering: to say it again how do I clear a file that already exists to just be blank?
Here is what I was thinking:
public void clearFile(){
//go through and do this every time in order to delete previous crap
while(s.hasNext()){
f.format(" ");
}
}
Best I could think of is :
Files.newBufferedWriter(pathObject , StandardOpenOption.TRUNCATE_EXISTING);
and
Files.newInputStream(pathObject , StandardOpenOption.TRUNCATE_EXISTING);
In both the cases if the file specified in pathObject is writable, then that file will be truncated. No need to call write() function. Above code is sufficient to empty/truncate a file.This is new in java 8.
Hope it Helps
You could delete the file and create it again instead of doing a lot of io.
if(file.delete()){
file.createNewFile();
}else{
//throw an exception indicating that the file could not be cleared
}
Alternately, you could just overwrite the contents of the file in one go as explained in the other answers :
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();
Also, you are using the constructor from Scanner that takes a String argument. This constructor will not read from a file but use the String argument as the text to be scanned. You should first created a file handle and then pass it to the Scanner constructor :
File file = new File("jibberish.txt");
Scanner scanner = new Scanner(file);
If you want to clear the file without deleting may be you can workaround this
public static void clearTheFile() {
FileWriter fwOb = new FileWriter("FileName", false);
PrintWriter pwOb = new PrintWriter(fwOb, false);
pwOb.flush();
pwOb.close();
fwOb.close();
}
Edit: It throws exception so need to catch the exceptions
You can just print an empty string into the file.
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();
type
new PrintWriter(PATH_FILE).close();
Better to use this:
public static void clear(String filename) throws IOException {
FileWriter fwOb = new FileWriter(filename, false);
PrintWriter pwOb = new PrintWriter(fwOb, false);
pwOb.flush();
pwOb.close();
fwOb.close();
}

How Can I Create A File In Java?

I am working on a program that needs a lot of app data. I am trying to create a function that creates a file with the path/file name of the string path. Here's my code:
public static void CreateFile(String path) throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter writer = new PrintWriter(path, "UTF-8");
writer.close();
}
What did I do wrong? Shouldn't it create a file?
you can refer to this code :
FileWriter fw = new FileWriter("C:\\FileW3.txt");// you can give path here
//or
FileOutputStream fos = new FileOutputStream("path name");
PrintWriter pw = new PrintWriter (new OutputStreamWriter(fos));
pw.write("Combo stream and writer + using PrintWriter's write() methood/n");
pw.println();
pw.println("now using PrintWriter's println() methood");
pw.flush();
pw.close();
Also
File f = new File("path and filename");
This wont create a file , the file object can be used as parameter in FileWriter or FileOutputStream to create and then write to that file.
File object is just abstract representation of file.
It seems that you want to create an empty file. For this, you can use Files.createFile or File.createNewFile (but it will require you to instantiate a File).
To create a non-empty file, just write something in it and it will be automatically created if it does not exist.
Please see this link in the doucmentation - Create a file object then call 'createNewFile()' method on the newly created object.

Java FileWriter not actually changing file at all

I have been looking for the past hour or so trying to find the reason for this, but have found nothing. It is a very small text file (only 4 characters at most), thus the reason I did not bother with a BufferedReader or BufferedWriter. The problem lies in the fact that while I have the writer put the variable into the file and even close the file, it does not actually keep the change in the file. I have tested this by checking the file immediately after running the method containing this code.
try {
int subtract = Integer.parseInt(secMessage[2]);
try {
String deaths = readFile("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt", Charset.defaultCharset());
FileWriter write = new FileWriter("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt");
int comb = Integer.parseInt(deaths) - subtract;
write.write(comb);
write.close();
sendMessage(channel, "Death count updated to " + comb);
} catch (IOException e) {
e.printStackTrace();
}
} catch (NumberFormatException e) {
e.printStackTrace();
sendMessage(channel, "Please use numbers to modify death count");
}
EDIT: Since it was asked, here is my readFile message:
static String readFile(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
I have already tested it and it returns the contents without error.
EDIT2: Posting the readFile method made me think of something to try, so I removed the call to it (code above also updated) and tried it again. It now writes to the file, but does not write what I want. New question will be made for this.
FileWriter write = new FileWriter(readFile("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt", Charset.defaultCharset()));
You're trying to write a file named after the contents of deaths.txt. It's possible that you intend to be writing to the file itself.
From http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html
FileWriter(String fileName)
Constructs a FileWriter object given a file name.
FileWriter write = new FileWriter(readFile("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt", Charset.defaultCharset()));
Currently you are using the contents of the file instead of the file name.

Writing to txt file from StringWriter

I have a StringWriter variable, sw, which is populated by a FreeMarker template. Once I have populated the sw, how can I print it to a text file?
I have a for loop as follows:
for(2 times)
{
template.process(data, sw);
out.println(sw.toString());
}
Right now, I am just outputting to the screen only. How do I do this for a file? I imagine that with each loop, my sw will get changed, but I want the data from each loop appended together in the file.
Edit:
I tried the code below. When it runs, it does show that the file.txt has been changed, but when it reloads, the file still has nothing in it.
sw.append("CheckText");
PrintWriter out = new PrintWriter("file.txt");
out.println(sw.toString());
How about
FileWriter fw = new FileWriter("file.txt");
StringWriter sw = new StringWriter();
sw.write("some content...");
fw.write(sw.toString());
fw.close();
and also you could consider using an output stream which you can directly pass to template.process(data, os); instead of first writing to a StringWriter then to a file.
Look at the API-doc for the template.process(...) to find out if such a facility is available.
Reply 2
template.process(Object, Writer) can also take a FileWriter object, witch is a subclass of Writer, as parameter, so you probably can do something like that:
FileWriter fw = new FileWriter("file.txt");
for(2 times)
{
template.process(data, fw);
}
fw.close();
You can use many different streams to write to file.
I personally like to work with PrintWriter here
You can flag to append in the FileWriter (the true in the following example):
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
out.println(sw.toString());
out.close();
} catch (IOException e) {
// Do something
}
Why not use a FileWriter ?
Open it before you loop and generate your required output. As you write to the FileWriter it'll append to the buffer and write out your accumulated output upon a close()
Note that you can open a FileWriter in overwrite or append mode, so you can append to existing files.
Here's a simple tutorial.
If you don't mind using Apache commons IO :
FileUtils.write(new File("file.txt"), sw.toString(), /*append:*/ true);

Categories

Resources