InputStreamReader is not reading č ž š characters - java

I'm working on a project, but when I am reading from file it can't read some characters (like č , ž , š, etc.) I dont know what am I am doing wrong.
Here is my code:
try {
reader = new InputStreamReader(getAssets().open("koce_podatki.txt"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(reader);
for(int i=-1;i<position;i++){
try {
temp = "" + br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Your problem is one of encoding. Files only store bytes.
There are many ways to map bytes to characters (those ways are called encoding).
When you read from a text file, you must know and specify which encoding to use.
If you don't specify the encoding in Java, the platform default encoding will be used, which may or may not be what you want.
In your case it is not what you want. To fix this, find out the correct encoding and specify it in the InputStreamReader constructor.
A common encoding to try would be UTF-8. If you told us what you see instead of those characters, we could help you guess the correct encoding.

Try this way:
try {
reader = new InputStreamReader(getAssets().open("koce_podatki.txt"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader in = new BufferedReader(reader);
while( (s = in.readLine()) != null) {
String UTF8Str = new String(s.getBytes(),"UTF-8"));
temp=""+UTF8Str;
}

Related

How do I print the next element in a linked list to a CSV file?

I'm making an address book and my program is supposed to save each element in a list to a CSV file. I've gotten everything to work asside from the fact that it will only save 1 line to the file.
public static void save(){
PrintWriter writer = null;
try {
writer = new PrintWriter("C:\\Users\\Remixt\\workspace\\2\\AddressBook.csv", "UTF-8");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(0);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(0);
}
{
writer.println(AddressBook.get(getListSize()-1)+"\n");
writer.close();//saves file
}
Edit: It will only save the last element to the file. It only shows 1 thing in the file no matter how many times i add something else to the list.
the problem is here
writer.println(AddressBook.get(getListSize()-1)+"\n");
you just write the last element of AddressBook to the csv file, use for loop
the following is a sample
for (int i = 0; i < AddressBook.size(); i++) {
writer.println(AddressBook.get(i)+"\n");
}
at last, you should write file by append mode
filename=new FileWriter("printWriter.txt",true);
writer=new java.io.PrintWriter(filename);

ReplaceAll not working on XML input

I am working on a java program that reads in XML and generates an output XML. I am having a problem replacing some of the characters in my read in file.
The following is my method:
public void readTemplateXML() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(
path), "UTF8"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
xml = sb.toString();
xml = xml.replaceAll("<", "\\<"); //This is not working.
}
I am just outputting the "xml" string to an xml file and I am still getting "<":
<addressLine1>Main Street</addressLine1>
Is there anyway I can replace these characters with <, > ?
The encoding of the file is UTF-8.
EDIT:
the xml string is correct after the replace alls. I am using it as text content in another methods xml node:
// inner request element
Element request = doc.createElement("con:request");
request.appendChild(doc.createTextNode(xml));
rootElement.appendChild(request);
After this the content is incorrect.
Any help would be greatly appreaciated.
short answer :
Syntax:
Here is the syntax of this method:
public String replaceAll(String regex, String replacement)
Parameters:
Here is the detail of parameters:
regex -- the regular expression to which this string is to be matched.
replacement -- the string which would replace found expression.
code :
String xml="<addressLine1>Main Street</addressLine1>&#13";
xml = xml.replaceAll("<", "\\<");
xml = xml.replaceAll(">", "\\>");
xml = xml.replaceAll("&#13", "");
System.out.println( xml );
result :
<addressLine1>Main Street</addressLine1>

Writing in files without overflow

I have the following code:
FileWriter filewriter = null;
try { filewriter = new FileWriter("outUser.txt", true); }
catch (IOException e1) { e1.printStackTrace(); }
try {
filewriter.write(s1+"\n");
filewriter.flush();
}
catch (IOException e1) { e1.printStackTrace(); }
Its supposed to write on outUser file the s1 string and a newline. It only writes s1, the newline is not written. I also tried with a new string that equals \n and append it to s1 when written but still didn't work. Do any of you have some answers for me?
The line feed should be there, but keep in mind that different OS-es have different new line characters.
If you're out of luck you can always try BufferedWriter.newLine().
Different OS have different ways to represent newlines.
For Example,\n is used in UNIX but \r\n is used in Windows.
This answers why windows uses \r
You can use System.lineSeparator() which returns the system-dependent line separator string.
Open your outUser.txt with an text editor like notepad++ and enable the 'non-printable'-chars. You should see an CR/LF, which is the \n.
The following should work
FileWriter filewriter = null;
try {
filewriter = new FileWriter("outUser.txt", true);
BufferedWriter buffWriter = new BufferedWriter(fileWriter);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
buffwriter.write(s1+"\n");
buffWriter.newLine();
buffwriter.flush();
}
catch (IOException e1) {
e1.printStackTrace();
}
Do like this
FileWriter filewriter = null;
try {
filewriter = new FileWriter("c:\\outUser.txt", true);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
filewriter.write("hi"+System.getProperty("line.separator"));
filewriter.write("asd");
filewriter.flush();
}
catch (IOException e1) {
e1.printStackTrace();
}
Use Line Separator Property to print nextline to File .

How do you put the content of a BufferedReader into a String?

Is there a way to place a BufferedReader into a String in one shot, rather than line by line? Here is what i have so far:
BufferedReader reader = null;
try
{
reader = read(filepath);
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String line = null;
String feed = null;
try
{
line = reader.readLine();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
while (line != null)
{
//System.out.println(line);
try
{
line = reader.readLine();
feed += line;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(feed);
You could use Apache FileUtils library for the same.
Using the StringBuilder and read(char[], int, int) methods would look like this, and is probably the most optimal way to do it in Java:
final MAX_BUFFER_SIZE = 256; //Maximal size of the buffer
//StringBuilder is much better in performance when building Strings than using a simple String concatination
StringBuilder result = new StringBuilder();
//A new char buffer to store partial data
char[] buffer = new char[MAX_BUFFER_SIZE];
//Variable holding number of characters that were read in one iteration
int readChars;
//Read maximal amount of characters avialable in the stream to our buffer, and if bytes read were >0 - append the result to StringBuilder.
while ((readChars = stream.read(buffer, 0, MAX_BUFFER_SIZE)) > 0) {
result.append(buffer, 0, readChars);
}
//Convert StringBuilder to String
return result.toString();
If you know the length of your input (or an upper bound to it) you can read the whole thing to a character array, using read(char[],int,int), then use that to build a String. It doesn't matter if your third parameter (len) is greater than the size, the method will return the number of characters read.
With Guava, CharStreams.toString(reader) does the job.

Java File I/O - Text File - How to check for content?

I was wondering, If i had a java class, that wanted to consult a txt file with say a list of names like
tom
steve
jones
how could i open the text file in the java program and basically see if a string contained in the program matches one of these names?
so far i have come up with
try {
BufferedReader inputReader = new BufferedReader(new FileReader("users.txt"));
while (inputReader.readLine() != null){
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException ep) {
// TODO Auto-generated catch block
p.printStackTrace();
}
but do not no where to go from here..
You need to store the result of readLine(), like:
String nextLine;
while ((nextLine = inputReader.readLine()) != null){
if (nextLine.equals(stringToCheck)) {
//do something
}
}
(where stringToCheck is the target string, of course.)

Categories