I am trying to get Japanese input from a JTextField (with the getText() method) and saving that to a File. I am confident that it does get Japanese format from the JTextField since I can append() that String to a JTextArea and it will be in the correct Japanese Format.
However, when I try to write to a File it only turns to gibberish! I have tried to use an OutputStreamWriter instantiated with StandardCharsets.UTF_8 and I have tried with a plain FileOutputStream where I send in the bytes from calling getBytes(StandardCharsets.UTF_8) on the String. In both cases the resulting file looks more like the following:
日本語ã�¯é›£ã�—ã�„ã�¨æ€�ã�†ï¼�å¦ã�³ã�Ÿã�„ã�ªã‚‰ã€�日本ã�§ä½�ã‚€
Which is not what I want, naturally. Does anyone have any idea what the issue might be?
I'm pretty sure you are creating the file with ISO-8859-1 instead UTF-8.
I'm also inferring you are using Eclipse because your previous questions.
Change your workspace settings
Window -> Preferences -> General -> Workspace : UTF-8
Default encoding for all content types
TestClass
This is the class i used to test the theory
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class test {
public static void main(String[] args) throws IOException {
File fileDir = new File("test.txt");
String japanese = "路権ち点節ヤトツ限聞ド勇売質タカア";
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileDir)));
out.append(japanese);
System.out.println(japanese);
out.flush();
out.close();
}
}
Input/output with different settings
OutputFileISO: 路権ã¡ç¹ç¯ã¤ããéèãå売質ã¿ã«ã¢
OutputFileUTF8: 路権ち点節ヤトツ限聞ド勇売質タカア
Related
I try to write chinese character but take a wrong result
For Instance :
import java.io.*;
import java.nio.*;
class x {
public static void main(String... args) throws Exception {
OutputStreamWriter outputStreamWriter =
new OutputStreamWriter(new FileOutputStream(new File("practice.csv"), true), "GBK");
outputStreamWriter.write("常用场景");
outputStreamWriter.write("Helo World!");
outputStreamWriter.flush();
outputStreamWriter.close();
}
}
Response : ????¡±¡§??????Helo World!
I tried to change charset utf-8, utf-16 but it doesn't anything and lastly I tried to add BufferedWriter but unfortunately it doesn't anything again.
then I considered to change csv to txt, but again same result. What am I doing wrong ?
I found it finally. Firstly very thanks for helping #Kayaman and #user16320675.
In fact, everything was correct. This problem's resource is csv files is opened by excel. When you want to open csv files directly in excel, it opens according to the encoding of the current computer language. We just have a option in Windows 10 EN(manually Data Import). I used the windows 10 EN and excel uses ANSI for windows 10 EN.
My Solution : I added to chinese language pack to my windows 10 computer and I changed the excel editing language (chinese for default) and everything worked.
To get a full idea, the project consists of a webpage with a download button that, when clicked, downloads a text file to the users computer. The webpage uses Javascript and PHP, which will call a Java AWS-Lambda function. The java grabs text from a database.
Originally, I had it working locally as so:
StreamFactory sf = StreamFactory.newInstance();
sf.loadResource("mapping.xml");
File file = new File("C:\\test.txt");
BeanWriter bw = sf.createWriter("export", file);
// beans written bellow
...
bw.write(recordName, bean);
However, due to the nature of using Lambda functions, I can't as easily save to the server as I could save to my local (would require SSH-ing in programatically, etc). In addition, my senior requested that I make my project not have to save files to the server, so we don't have to manage deleting them later.
I've now been attempting to do it like this:
StreamFactory sf = StreamFactory.newInstance();
sf.loadResource("mapping.xml");
OutputStreamWriter output;
BeanWriter bw = sf.createWriter("export", output);
// beans written bellow
...
bw.write(recordName, bean);
I've read that createWriter can use a writer instead of a file, but I don't understand how that could be utilized within the javascript side to download as a file. Currently, the code on that end is simple and looks like this:
Download
This project is not using servlets. My senior is adament about using AWS-Lambda and writing to a stream. It needs to use BeanIO. Most of the similar questions I've seen do not have these as challenges, so this question shouldn't be closed for being a duplicate.
I have no knowledge about AWS-Lambda, but googling got me to Leveraging Predefined Interfaces for Creating Handler (Java), specifically Example 2: Creating Handler with Stream Input/Output (Leverage the RequestStreamHandler Interface). From the article you could then use the Outputstream provided by the interface to write your response back to the user.
This would HOPEFULLY trigger something similar to a file download request and then the browser could either display the result or ask the user to save the response as a file on their computer.
Combining that with your code:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import org.beanio.BeanWriter;
import org.beanio.StreamFactory;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import com.amazonaws.services.lambda.runtime.Context;
public class HelloBeanIO implements RequestStreamHandler {
public void handleRequest(InputStream inputStream,
OutputStream outputStream,
Context context)
throws IOException {
StreamFactory sf = StreamFactory.newInstance();
sf.loadResource("mapping.xml");
// wrap the supplied OutputStream in a OutputStreamWriter
// and set the encoding you prefer
OutputStreamWriter writer = new OutputStreamWriter(outputStream,
StandardCharsets.UTF_8);
BeanWriter bw = sf.createWriter("export", writer);
// beans written bellow
...
bw.write(recordName, bean);
}
}
The important part is that you wrap the OutputStream passed into the method with a OutputStreamWriter.
There are most likely more things to do to get it working properly, somehow maybe setting the correct mime type for the response could change the behaviour of how the browser handles the response.
There is something wrong with GZIPInputStream or GZIPOutputStream. Just please read the following code (or run it and see what happens):
def main(a: Array[String]) {
val name = "test.dat"
new GZIPOutputStream(new FileOutputStream(name)).write(10)
println(new GZIPInputStream(new FileInputStream(name)).read())
}
It creates a file test.dat, writes a single byte 10 formatting by GZIP, and read the byte in the same file with the same format.
And this is what I got running it:
Exception in thread "main" java.io.EOFException: Unexpected end of ZLIB input stream
at java.util.zip.InflaterInputStream.fill(Unknown Source)
at java.util.zip.InflaterInputStream.read(Unknown Source)
at java.util.zip.GZIPInputStream.read(Unknown Source)
at java.util.zip.InflaterInputStream.read(Unknown Source)
at nbt.Test$.main(Test.scala:13)
at nbt.Test.main(Test.scala)
The reading line seems going the wrong way for some reason.
I googled the error Unexpected end of ZLIB input stream and found some bug reports to Oracle, which were issued around 2007-2010. So I guess the bug still remains in some way, but I'm not sure if my code is right, so let me post this here and listen to your advice. Thank you!
You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the stream object is actually closed.
(This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() won't help ... though calling finish() instead of close() should work. Look at the javadocs.)
Here's the correct code (in Java);
package test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZipTest {
public static void main(String[] args) throws
FileNotFoundException, IOException {
String name = "/tmp/test";
GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
gz.write(10);
gz.close(); // Remove this to reproduce the reported bug
System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
}
}
(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)
I'm creating a log in form in Java and I've added a remember me method to store the log in data in a local text file for future us.
The premise is that once the checkbox is checked, the email and password gets written out to the text file.
Here's the code below:
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
public void rememberMe() throws IOException {
private final ArrayList<String> storage = new ArrayList<String>();
protected String storPass;
protected String storEmail;
storage.add(storEmail);
storage.add(storPass);
FileWriter writer = new FileWriter("local.txt");
for(String i : storage) {
writer.write(i);
System.out.println("We have written " + i);
}
writer.close();
}
with the output being:
We have written EMAILADDRESS
We have written PASSWORD
The data has been removed, but the printing in the foreach look is showing me that it's cycling through the Arraylist correctly.
The local.txt doesn't have any data in it, it's empty before running and empty during and after the program is ran.
Can anybody spot the problem I'm having?
Thanks in advance.
Instead of Using relative path use absolute path like D:\\local.txt. It will work
Try using:
Path locates/creates the file on the system
Then use the Files object to statically write the file using your list.
Path file = Paths.get("local.txt");
Files.write(file, storage, Charset.forName("UTF-8"));
This way you can stay away from writing explicit foreach loop.
here is more on the Files object which is available since java 1.7+
https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
I have a class that reads a file:
package classlibrary;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
public class ReadingResource {
public static String readResource() throws IOException {
URL resource = ClassLoader.getSystemClassLoader().getResource("classlibrary/test_file.txt");
BufferedReader br = new BufferedReader(new FileReader(resource.getPath()));
return br.readLine();
}
}
The resource file is in the same directory where this class is.
I made a library out of this class and the file.
Now I want to use it in the other class:
package uritesting;
import classlibrary.ReadingResource;
import java.io.IOException;
public class URITesting {
public static void main(String[] args) throws IOException {
System.out.println(ReadingResource.readResource());
}
}
When I make a .jar file out of this class, set the class as the main class, add the .jar from above and execute it as "java -jar URITesting.jar" I get a FileNotFoundException, saying the class ReadingResource can not find the specified file. It is funny because the path that is specified in the exception message is actually the correct path to the file.
You can find the files here.
EDIT:
I developed the project in NetBeans. When I run it there, it works fine. The classpath is different in that case. It contains both resources of the URITestingProject and ReadingResource.
However, when I run it as a standalone JAR, the classpath contains URITestingProject only. What is strange to me is that it doesn't complain about not finding the class ReadingResource. It means that it is loaded, although it is not in the classpath :/
The problem is resource.getPath(). It's not possible to calculate a path ,valid for a file reader, inside a jar file, on another server and so on. However you can get the data through a stream instead:
InputStream data = ClassLoader.getSystemClassLoader().getResourceAsStream("classlibrary/test_file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(data, "utf-8"));
As a side note: When reading with reader it's a good idea to specify the encoding: