Reading a txt file (weird symbols) JAVA - java

im trying to read a txt file downloaded from an arduino server. I can download the file and save it on internal storage, but when i want to read it, i see weird symbols and i can't see all saved text, only 6 o 7 characters. I don't know what happen.
public void downloadFile (String fileDownloadPath, String saveFilePath){
try{
File SaveFile = new File(saveFilePath);
URL u= new URL ("http://169.254.0.1:44300/169.254.0.1");
URLConnection con=u.openConnection();
int lengthofContent=con.getContentLength();
DataInputStream DIStream = new DataInputStream(u.openStream());
byte [] buffer = new byte[2000];
DIStream.read(buffer);
DIStream.close();
DataOutputStream DOStream = new DataOutputStream(new FileOutputStream(SaveFile));
DOStream.write(buffer);
DOStream.flush();
DOStream.close();
System.out.println ("o");
hideProgressIndicator();
} catch (FileNotFoundException e){
hideProgressIndicator();
}
catch (IOException e){
hideProgressIndicator();
}
catch (Exception e){
}
}
when i want to read it i use this:
private String readFile() {
String result = "", line;
try
{
BufferedReader br = new BufferedReader((new FileReader("/data/data/com.example.sensolog/files/LOL.txt")));
while((line = br.readLine()) != null)
{
result += line + "\n";
}
System.out.println (result);
br.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return result ;
}
And the results are the followings :
08-26 15:38:11.498: I/System.out(30593): SERVIDORn�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������...

Define the encoding of the file while reading, here is an example:
BufferedReader br = new BufferedReader(( new FileReader("/data/data/com.example.sensolog/files/LOL.txt"),"ISO-8859-1"));

You're downloading and storing the file as a DataOutputStream - Which can only be read again by a DataInputStream - Is that your intention? I would save the file as a simple text file, unless you absolutely must save as a binary type?
Further information on DataOutputStream:
Wraps an existing OutputStream and writes big-endian typed data to it. Typically, this stream can be read in by DataInputStream. Types that can be written include byte, 16-bit short, 32-bit int, 32-bit float, 64-bit long, 64-bit double, byte strings, and MUTF-8 encoded strings. from: http://developer.android.com/reference/java/io/DataOutputStream.html

Related

Can't read from binary file - read some lines in UTF-8, some in binary

I have this code:
import java.io.*;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) {
zero("zero.out");
System.out.println(zeroRead("zero.out"));
}
public static String zeroRead(String name) {
try (FileInputStream fos = new FileInputStream(name);
BufferedInputStream bos = new BufferedInputStream(fos);
DataInputStream dos = new DataInputStream(bos)) {
StringBuffer inputLine = new StringBuffer();
String tmp;
String s = "";
while ((tmp = dos.readLine()) != null) {
inputLine.append(tmp);
System.out.println(tmp);
}
dos.close();
return s;
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void zero(String name) {
File file = new File(name);
String text = "König" + "\t";
try (FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
DataOutputStream dos = new DataOutputStream(bos)) {
dos.write(text.getBytes(StandardCharsets.UTF_8));
dos.writeInt(50);
} catch (IOException e) {
e.printStackTrace();
}
}
}
zero() method writes data into file: the string is written in UTF-8, while the number is written in binary. zeroRead() read the data from file.
The file looks like this after zero() is executed:
This is what zeroRead() returns:
How do I read the real data König\t50 from the file?
DataInputStream's readLine method has javadoc that is almost yelling that it doesn't want to be used. You should heed this javadoc: That method is bad and you should not use it. It doesn't do charset encoding.
Your file format is impossible as stated: You have no idea when to stop reading the string and start reading the binary numbers. However, the way you've described things, it sounds like the string is terminated by a newline, so, the \n character.
There is no easy 'just make this filter-reader and call .nextLine on it available, as they tend to buffer. You can try this:
InputStreamReader isr = new InputStreamReader(bos, StandardCharsets.UTF_8);
However, basic readers do not have a readLine method, and if you wrap this in a BufferedReader, it may read past the end (the 'buffer' in that name is not just there for kicks). You'd have to handroll a method that fetches one character at a time, appending them to a stringbuilder, ending on a newline:
StringBuilder out = new StringBuilder();
for (int c = isr.read(); c != -1 && c != '\n'; c = isr.read())
out.append((char) c);
String line = out.toString();
will get the job done and won't read 'past' the newline and gobble up your binary number.

Issues writing doubles to files, writing nothing

I seem to be missing something when it comes to writing doubles to text files, when I check the file, just blank space is present. When I read from the file and print with System.out.println(); it just prints nothing... What's going wrong here? Do I need to do some converting?
import java.io.*;
import javax.swing.JOptionPane;
public class ReadCalcAveragePrint {
double firstNum;
double secondNum;
double average;
public void readFile() {
try {
File f = new File("numbers.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
String one = br.readLine();
String two = br.readLine();
firstNum = Double.parseDouble(one);
secondNum = Double.parseDouble(two);
average = (firstNum + secondNum) / 2;
JOptionPane.showMessageDialog(null, average, "title", JOptionPane.PLAIN_MESSAGE);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
public void writeFile() {
try {
File f = new File("result.txt");
FileOutputStream fos = new FileOutputStream(f);
DataOutputStream dos = new DataOutputStream(fos);
dos.writeDouble(average);
dos.flush();
fos.close();
System.out.println("Printed.");
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
public void readResult() {
try {
File f = new File("result.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
String one = br.readLine();
System.out.println(one);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
public static void main(String[] args) {
new ReadCalcAveragePrint().readFile();
new ReadCalcAveragePrint().writeFile();
new ReadCalcAveragePrint().readResult();
}
}
In the main you are creating 3 different objects, only the first is going to contain the numbers you read from the file.
You should just create and reuse one object:
public static void main(String[] args) {
ReadCalcAveragePrint obj = new ReadCalcAveragePrint();
obj.readFile();
obj.writeFile();
obj.readResult();
}
Also you are writing the result file using DataOutputStream which is meant to write the data in binary form. If you just want to save the result as text you should use FileWriter instead:
File f = new File("result.txt");
FileWriter fw = new FileWriter(f);
fw.write(String.valueOf(average));
fw.close();
see the javadoc of writeDouble:
Converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the underlying output stream as an 8-byte quantity, high byte first.
you write 8 bytes that may not be assigned to any alphanumeric character. Then you read it a line as a String (characters up to the next 'new line' char).
In this case, the 'new line' char can be anywhere, or nowhere (depending on the result).
8 bytes in file means almost 4 chars, very likely, no one is a "visible character".
Try to read a byte[8] from the InputStream (not from a Buffered one), and then put those 8 bytes into DoubleBuffer, then you can get the double value represented by those bytes and writen to the file before.

Read text file at one step [duplicate]

This question already has answers here:
What is simplest way to read a file into String? [duplicate]
(9 answers)
Java 1.4.2 - Reading Files
(3 answers)
Closed 7 years ago.
I need to read text file to String. I do :
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filePath));
String line = br.readLine();
String everything = line;
while (line != null) {
line = br.readLine();
everything += line + "\n";
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
But I dont like to read line by line. It should be possible to read whole file to string at one function call. I'm right? By the way, I must use java 1.4.
you can read the whole file data as byte array.
File file = new File(yourFileName);
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();
String strData=new String(data, "UTF-8"); // converting byte array to string
System.out.println(strData);
If you are allowed to use an external library, you could have a look on Apache Commons FileUtils
Besides, you definitely should not use such an old java version.

Reading a line with multiple line breaks as separate lines

I have java program which is running on mainframe z/os and is reading a EBCDIC file. Few of the lines in the file have multiple records separated by EBCDIC 'LF' X'025'. I am using Java readline and as expected it is reading the record till linefeed and discarding rest of the records. Besides parsing the big line into multiple records, is there any way to make the read methods split the line into multiple lines/records and return the same? If needed, I do have the option to change the new-line delimiter to any values.
Input:
10,IBM,ERWIN,BLACK,123,ABC(LF)10,IBM,JACK,ROSE,456
Expected output
10,IBM,ERWIN,BLACK,123,ABC
10,IBM,JACK,ROSE,456
Current Code:
public ArrayList<String> readMainframeFile()
{
//String DDNAME = ZFile.allocDummyDDName();
//System.out.println("The DDName is " + DDNAME);
//ZFile convout = new ZFile("//DD:CONVOUT", "wb,type=record,noseek");
//RecordReader reader=null;
try {
ZFile convin = new ZFile("//DD:CONVIN", "rb,type=record,noseek");
System.out.println("The DDName is" + convin.getLrecl());
byte[] recordBuf = new byte[convin.getLrecl()];
int bytesRead=0;
InputStream ins = null;
BufferedReader reader = null;
String temp=null;
ArrayList<String> lines = new ArrayList<String>();
while((bytesRead = convin.read(recordBuf)) > 0) {
//System.out.println("The number of bytes read is" + bytesRead);
try {
ins = new ByteArrayInputStream(recordBuf);
reader = new BufferedReader(new InputStreamReader(ins,Charset.forName("ibm500")));
temp=reader.readLine();
lines.add(temp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
return lines;
} catch (ZFileException e) {
System.err.println(e.getMessage());
return null;
}
}
You're opening the file for QSAM binary I/O when you should be opening it as a text file stream.
ZFile convin = new ZFile("//DD:CONVIN", "r");
Then just read the records as you normally would with a stream. There's no need for an additional line reader. z/OS UNIX newlines are usually x'15' so you may need to change your linefeed character.

First letter missing when reading a file

I am retrieving data from a file and for some reason i miss the first char every time.
my code.
public String readFile(){
String str = "Not Authenticated";
//Reading the file
try{
FileInputStream fIn = openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[isr.read()]; //str.length()
// Fill the Buffer with data from the file
try {
isr.read(inputBuffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
// Transform the chars to a String
String readString = new String(inputBuffer);
str = readString;
} catch (IOException ioe)
{return ioe.toString();}
return str;
}
the file contains the word "True"
i get "rue"
also when i create the file the first letter cannot be a capital? if i use a capital the file is never found i am guessing the two are not related.
If that file is text file then read it via BufferedReader.
StringBuilder sb=new StringBuilder();
BufferedReader br=null;
try{
br=new BufferedReader(new InputStreamReader(openFileInput(fileName));
String line=null;
while((line = br.readLine()) != null)
{
sb.append(line);
}
}catch(Exception ex){
//
}finally{
if(br!=null)
br.close();
}
return sb.toString();
char[] inputBuffer = new char[isr.read()]; //str.length()
Does this not read a character out of your reader?
EDIT: http://docs.oracle.com/javase/1.4.2/docs/api/java/io/InputStreamReader.html
isr.read() will read a single character (ie. the first character).
To get the size of the file, you can use
long length = new File(fileName).length()
See File.length() function for details.
You can use File class to find length of a file,:
File f=new File("c:\\new\\abc.txt");
f.length(); will return size in bytes
You should also close the file opened. by isr.close();

Categories

Resources