Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I saved my Java source file specifying it's encoding type as UTF-8 in my eclipse. It is working fine in eclipse.
When I create a build with maven & execute it in my system Unicode characters are not working.
This is my code :
byte[] bytes = new byte[dataLength];
buffer.readBytes(bytes);
String s = new String(bytes, Charset.forName("UTF-8"));
System.out.println(s);
Eclipse console & windows console screenshot attached.
Expecting eclipse output in other systems(windows command prompt, powershell window, Linux machine, etc.,).
You could use the Console class for that.The following code could give you some inspiration:
public class Foo {
public static void main(String[] args) throws IOException {
String s = "öäü";
write(s);
}
private static void write(String s) throws IOException {
String encoding = new OutputStreamWriter(System.out).getEncoding();
Console console = System.console();
if (console != null) {
// if there is a console attached to the jvm, use it.
System.out.println("Using encoding " + encoding + " (Console)");
try (PrintWriter writer = console.writer()) {
writer.write(s);
writer.flush();
}
} else {
// fall back to "normal" system out
System.out.println("Using encoding " + encoding + " (System out)");
System.out.print(s);
}
}
}
Tested on Windows 10(poowershell), Ubuntu 16.04(bash) with default settings. Also works from within IntelliJ (Windows and Linux).
From what I can tell, you either have the wrong character, which I don't think is the case, or you are trying to display it on a terminal that doesn't handle the character. I have written a short test to separate the issues.
public static void main(String[] args){
String testA = "ֆޘᜅᾮ";
String testB = "\u0586\u0798\u1705\u1FAE";
System.out.println(testA.equals(testB));
System.out.println(testA);
System.out.println(testB);
try(BufferedWriter check = Files.newBufferedWriter(
Paths.get("uni-test.txt"),
StandardCharsets.UTF_8,
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING) ){
check.write(testA);
check.write("\n");
check.write(testB);
check.close();
} catch(IOException ioc){
}
}
You could replace the values with the characters you want.
The first line should print out true if the string is the actual string you want. After that it is a matter of displaying the characters. For example if I open the text file with less then half of them are broken. If I open it with firefox, then I see all four characters, but some are wonky. You'll need a font that has characters for the corresponding unicode value.
One thing you can do is open the file in a word processor and select a font that displays the characters you want correctly.
As suggested by the OP, including the -Dfile.encoding=UTF8causes the characters to display correctly when using System.out.println. Similar to this question which changes the encoding of System.out.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have a file dictionary.txt and I need to get that file from the raw folder so I googled around and found this:
Here's an example:
"android.resource:///"+getPackageName()+ "/" + R.raw.dictionary;
but it did not work, Any idea?
Edit:
here is what i am doing
for(String line: FileUtils.readLines(file))
{
if(line.toLowerCase().equals(b.toLowerCase()))
{
valid = true;
}
}
You can get an input stream on a raw resource by using:
getResources().openRawResource(R.raw.dictionary);
EDIT:
From your edit, there really isn't a reason as to why you would specifically need the file rather than just using the input stream available from the openRawResource(int id) method...just use an existing java class http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner%28java.io.InputStream,%20java.lang.String%29.
Scanner scanner = new Scanner(getResources().openRawResource(R.raw.dictionary));
while(scanner.hasNextLine()){
{
if(scanner.nextLine().toLowerCase().equals(b.toLowerCase()))
{
valid = true;
}
}
}
Unfortunately you can not create a File object directly from the raw folder. You need to copy it in your sdcard or inside the application`s cache.
you can retrieve the InputStream for your file this way
InputStream in = getResources().openRawResource(R.raw.yourfile);
try {
int count = 0;
byte[] bytes = new byte[32768];
StringBuilder builder = new StringBuilder();
while ( (count = is.read(bytes,0 32768) > 0) {
builder.append(new String(bytes, 0, count);
}
is.close();
reqEntity.addPart(new FormBodyPart("file", new StringBody(builder.toString())));
} catch (IOException e) {
e.printStackTrace();
}
EDIT:
to copy it over to internal storage:
File file = new File(this.getFilesDir() + File.separator + "fileName.ext");
try {
InputStream inputStream = resources.openRawResource(R.id._your_id);
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0) {
fileOutputStream.write(buf,0,len);
}
fileOutputStream.close();
inputStream.close();
} catch (IOException e1) {}
Now you have a File that you can access anywhere you need it.
Place the file in the assets folder and open it like this
getResources().getAssets().open("dictionary.txt");
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm creating a sport prediction game for my Grade 11 year and I'm having issues writing data to a text file. I'm using NetBeans 7.3.1. I'm using a button where every time it is pressed data entered by the user must be written to the text file. The text file is empty in the beginning and I need to add data to it. After the first click on the button the data keep rewriting itself and the new data is not added. It needs to be in a new line each time. Thank you very much. Some coding would be awesome!
I just did a quick search for appending to a file (usually a good thing to do): this question seems to be what your looking for.
I haven't tested this, but this should work:
private boolean appendToFile(String fileName, String data, String lineSeparator)
throws IOException {
FileWriter writer = null;
File file = new File(fileName)
if (!file.exists()) {
file.createNewFile();
}
try {
writer = new FileWriter(fileName, true);
writer.append(data);
writer.append(lineSeparator);
} catch (IOException ioe) {
return false;
} finally {
if (writer != null) {
writer.close();
}
}
return true;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm studying Chinese.
I have an iPhone app with optical character recognizer that can capture vocab lists in this format: (character TAB pronunciation TAB definition)
淫秽 TAB yin2hui4 TAB obscene; salacious; bawdy
网站 TAB wang3zhan4 TAB website
专项 TAB zhuan1xiang4 TAB attr. earmarked
but the flashcard app I use requires this format: (Character NEWLINE Pronunciation NEWLINE Definition)
淫秽
yin2hui4
obscene; salacious; bawdy
网站
wang3zhan4
<computing> website
专项
zhuan1xiang4
attr. earmarked
I only know a little Java. How do I convert the first format to the second format?
Obviously, we don't want to do your homework. But we don't want to leave you stranded either.
I've left many things open and the below is just a Java-looking pseudocode. You can start here...
FileReader reader = ... // open the file reader using the input file
FileWriter writer = ...// open a file for writing output
while(the stream doesn't end) { // provide the condition, as must be
String line = ... // read a line from the reader
String character = line.substring(0, line.indexOf("\t")),
pronounciation = line.substring(character.length() -1).substring(line.indexOf("\t", character.length()),
definition = line.substring(line.lastIndexOf("\t")); // Obviously, this isn't accurate.... you need to work around this.
writeLineToFile(character)
writeLineToFile(pronounciation)
writeLineToFile(definition)
}
close the reader and writer
Even though it looks like an Exercise. But ideally you can do.
Get the file contents (use commons-io)
Replace TAB with new line and write to file
example code
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class Test {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
String path = "C:/test.txt";
// TODO Auto-generated method stub
File file = new File(path);
String string = FileUtils.readFileToString(file);
String finalString = string.replaceAll("\t", "\n");
FileUtils.write(file, finalString);
}
}
The file now would look like
淫秽
yin2hui4
obscene; salacious; bawdy
网站
wang3zhan4
website
专项
zhuan1xiang4
attr. earmarked
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
Is there a way to read a text file in the resource into a String?
I suppose this is a popular requirement, but I couldn't find any utility after Googling.
Yes, Guava provides this in the Resources class. For example:
URL url = Resources.getResource("foo.txt");
String text = Resources.toString(url, StandardCharsets.UTF_8);
You can use the old Stupid Scanner trick oneliner to do that without any additional dependency like guava:
String text = new Scanner(AppropriateClass.class.getResourceAsStream("foo.txt"), "UTF-8").useDelimiter("\\A").next();
Guys, don't use 3rd party stuff unless you really need that. There is a lot of functionality in the JDK already.
Pure and simple, jar-friendly, Java 8+ solution
This simple method below will do just fine if you're using Java 8 or greater:
/**
* Reads given resource file as a string.
*
* #param fileName path to the resource file
* #return the file's contents
* #throws IOException if read fails for any reason
*/
static String getResourceFileAsString(String fileName) throws IOException {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
try (InputStream is = classLoader.getResourceAsStream(fileName)) {
if (is == null) return null;
try (InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr)) {
return reader.lines().collect(Collectors.joining(System.lineSeparator()));
}
}
}
And it also works with resources in jar files.
About text encoding: InputStreamReader will use the default system charset in case you don't specify one. You may want to specify it yourself to avoid decoding problems, like this:
new InputStreamReader(isr, StandardCharsets.UTF_8);
Avoid unnecessary dependencies
Always prefer not depending on big, fat libraries. Unless you are already using Guava or Apache Commons IO for other tasks, adding those libraries to your project just to be able to read from a file seems a bit too much.
For java 7:
new String(Files.readAllBytes(Paths.get(getClass().getResource("foo.txt").toURI())));
For Java 11:
Files.readString(Paths.get(getClass().getClassLoader().getResource("foo.txt").toURI()));
yegor256 has found a nice solution using Apache Commons IO:
import org.apache.commons.io.IOUtils;
String text = IOUtils.toString(this.getClass().getResourceAsStream("foo.xml"),
"UTF-8");
Guava has a "toString" method for reading a file into a String:
import com.google.common.base.Charsets;
import com.google.common.io.Files;
String content = Files.toString(new File("/home/x1/text.log"), Charsets.UTF_8);
This method does not require the file to be in the classpath (as in Jon Skeet previous answer).
apache-commons-io has a utility name FileUtils:
URL url = Resources.getResource("myFile.txt");
File myFile = new File(url.toURI());
String content = FileUtils.readFileToString(myFile, "UTF-8"); // or any other encoding
I like akosicki's answer with the Stupid Scanner Trick. It's the simplest I see without external dependencies that works in Java 8 (and in fact all the way back to Java 5). Here's an even simpler answer if you can use Java 9 or higher (since InputStream.readAllBytes() was added at Java 9):
String text = new String(AppropriateClass.class.getResourceAsStream("foo.txt")
.readAllBytes());
If you're concerned about the filename being wrong and/or about closing the stream, you can expand this a little:
String text = null;
InputStream stream = AppropriateClass.class.getResourceAsStream("foo.txt");
if (null != stream) {
text = stream.readAllBytes();
stream.close()
}
You can use the following code form Java
new String(Files.readAllBytes(Paths.get(getClass().getResource("example.txt").toURI())));
I often had this problem myself. To avoid dependencies on small projects, I often
write a small utility function when I don't need commons io or such. Here is
the code to load the content of the file in a string buffer :
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("path/to/textfile.txt"), "UTF-8"));
for (int c = br.read(); c != -1; c = br.read()) sb.append((char)c);
System.out.println(sb.toString());
Specifying the encoding is important in that case, because you might have
edited your file in UTF-8, and then put it in a jar, and the computer that opens
the file may have CP-1251 as its native file encoding (for example); so in
this case you never know the target encoding, therefore the explicit
encoding information is crucial.
Also the loop to read the file char by char seems inefficient, but it is used on a
BufferedReader, and so actually quite fast.
If you want to get your String from a project resource like the file
testcase/foo.json in src/main/resources in your project, do this:
String myString=
new String(Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource("testcase/foo.json").toURI())));
Note that the getClassLoader() method is missing on some of the other examples.
Here's a solution using Java 11's Files.readString:
public class Utils {
public static String readResource(String name) throws URISyntaxException, IOException {
var uri = Utils.class.getResource("/" + name).toURI();
var path = Paths.get(uri);
return Files.readString(path);
}
}
Use Apache commons's FileUtils. It has a method readFileToString
I'm using the following for reading resource files from the classpath:
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Scanner;
public class ResourceUtilities
{
public static String resourceToString(String filePath) throws IOException, URISyntaxException
{
try (InputStream inputStream = ResourceUtilities.class.getClassLoader().getResourceAsStream(filePath))
{
return inputStreamToString(inputStream);
}
}
private static String inputStreamToString(InputStream inputStream)
{
try (Scanner scanner = new Scanner(inputStream).useDelimiter("\\A"))
{
return scanner.hasNext() ? scanner.next() : "";
}
}
}
No third party dependencies required.
At least as of Apache commons-io 2.5, the IOUtils.toString() method supports an URI argument and returns contents of files located inside jars on the classpath:
IOUtils.toString(SomeClass.class.getResource(...).toURI(), ...)
With set of static imports, Guava solution can be very compact one-liner:
toString(getResource("foo.txt"), UTF_8);
The following imports are required:
import static com.google.common.io.Resources.getResource
import static com.google.common.io.Resources.toString
import static java.nio.charset.StandardCharsets.UTF_8
package test;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
String fileContent = getFileFromResources("resourcesFile.txt");
System.out.println(fileContent);
} catch (Exception e) {
e.printStackTrace();
}
}
//USE THIS FUNCTION TO READ CONTENT OF A FILE, IT MUST EXIST IN "RESOURCES" FOLDER
public static String getFileFromResources(String fileName) throws Exception {
ClassLoader classLoader = Main.class.getClassLoader();
InputStream stream = classLoader.getResourceAsStream(fileName);
String text = null;
try (Scanner scanner = new Scanner(stream, StandardCharsets.UTF_8.name())) {
text = scanner.useDelimiter("\\A").next();
}
return text;
}
}
Guava also has Files.readLines() if you want a return value as List<String> line-by-line:
List<String> lines = Files.readLines(new File("/file/path/input.txt"), Charsets.UTF_8);
Please refer to here to compare 3 ways (BufferedReader vs. Guava's Files vs. Guava's Resources) to get String from a text file.
Here is my approach worked fine
public String getFileContent(String fileName) {
String filePath = "myFolder/" + fileName+ ".json";
try(InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath)) {
return IOUtils.toString(stream, "UTF-8");
} catch (IOException e) {
// Please print your Exception
}
}
If you include Guava, then you can use:
String fileContent = Files.asCharSource(new File(filename), Charset.forName("UTF-8")).read();
(Other solutions mentioned other method for Guava but they are deprecated)
The following cods work for me:
compile group: 'commons-io', name: 'commons-io', version: '2.6'
#Value("classpath:mockResponse.json")
private Resource mockResponse;
String mockContent = FileUtils.readFileToString(mockResponse.getFile(), "UTF-8");
I made NO-dependency static method like this:
import java.nio.file.Files;
import java.nio.file.Paths;
public class ResourceReader {
public static String asString(String resourceFIleName) {
try {
return new String(Files.readAllBytes(Paths.get(new CheatClassLoaderDummyClass().getClass().getClassLoader().getResource(resourceFIleName).toURI())));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
class CheatClassLoaderDummyClass{//cheat class loader - for sql file loading
}
I like Apache commons utils for this type of stuff and use this exact use-case (reading files from classpath) extensively when testing, especially for reading JSON files from /src/test/resources as part of unit / integration testing. e.g.
public class FileUtils {
public static String getResource(String classpathLocation) {
try {
String message = IOUtils.toString(FileUtils.class.getResourceAsStream(classpathLocation),
Charset.defaultCharset());
return message;
}
catch (IOException e) {
throw new RuntimeException("Could not read file [ " + classpathLocation + " ] from classpath", e);
}
}
}
For testing purposes, it can be nice to catch the IOException and throw a RuntimeException - your test class could look like e.g.
#Test
public void shouldDoSomething () {
String json = FileUtils.getResource("/json/input.json");
// Use json as part of test ...
}
public static byte[] readResoureStream(String resourcePath) throws IOException {
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
InputStream in = CreateBffFile.class.getResourceAsStream(resourcePath);
//Create buffer
byte[] buffer = new byte[4096];
for (;;) {
int nread = in.read(buffer);
if (nread <= 0) {
break;
}
byteArray.write(buffer, 0, nread);
}
return byteArray.toByteArray();
}
Charset charset = StandardCharsets.UTF_8;
String content = new String(FileReader.readResoureStream("/resource/...*.txt"), charset);
String lines[] = content.split("\\n");