Binary File reading in Java
can i read binary format file with java? if so, can you please suggest which class i should be looking into?
Thanks
FileInputStream
Similar Messages
-
Hello everyone,
I am not that comfortable with binary file reading. I am trying to learn.
I have a vi which logs a sine wave in a binary file.
The Read vi which I have written is not giving the expected data.
Thanks in advance
cooldude
Attachments:
Log Data.vi 9 KB
Read Data.vi 10 KBAttachments:
Log.JPG 20 KB
Read.JPG 13 KB -
Hi,
I'm currently using a java.io.BufferedInputStream to read a large binary file.
I recently discovered there is a chunk of data that shows up near the end of each file. (these files are binary and are XX to XXX mb in size)
Loading it all to memory first would kill my performance so I'd like to be able to come up with an alternate method.
Does Java or the class above offer a way I can
1) get the length of the file
2) seek to a point say 2000 bytes from the end so I can start reading the binary data?
Ideally I'd like to do a backwards read as that would be quickest. Is there a way to change the operation so that a 'read' would be reading backwards (from end to beginning)?
For me speed is the #1 thing i have to worry about. So to be able to seek forward several hundred thousand bytes at a time would help tremendously.how does the 'skip' method work? Probably by using OS specific calls to read to a point in the file.
maybe I could
'skip' length - 20k from the start or something like
that.
Yep. -
I tried to read one line of binary file as the top of the screenshot.
The result is as the left side. It shows the first part with text are correct. The ending part is not match with the raw one.
I also tried read by byte, but still the same.
Any suggestion, thanks.
Solved!
Go to Solution.
Attachments:
shot.JPG 48 KBWhat program created this binary file?
If you can figure out how the file was created, then you can figure out how to read it.
We can't help because all you've shown are some bytes and say that some are right and some are wrong. What is the "raw one" you are referring to? What do you expect it to look like?
Message Edited by Ravens Fan on 01-26-2010 11:15 PM -
Binary file read with bit offset..not byte offset.
hi,
i want to read a binary file with some offset ..not in bytes... offset in bits..my data is a single bit data stream size of 1GB ,after skipping particular bit offset i want to read the data in byte order..
Indrajit
| [email protected] | [email protected] .hi , Gerd W
i am not able to follow your answer.... here with i attached a file to describe my query more clearly. Actually two channels of 1 bit data stream stored in two different files ,and the file size will be more than 10 GB.
i want to delay the channel B by 3 bits and i want to perform bitwise operation between channel A and shifted version of channel B..till the end of the data..
now i am doing this without applying any delay by choosing a small block by block which corresponds to 1 sec of data .
Indrajit
| [email protected] | [email protected] .
Attachments:
bitwsie.png 16 KB
bitwsie.jpg 52 KB -
Binary file readed from Labview and Borland C++ v.5
Hi Everybody!
My problem is reading binary file from Labview 7.0 and Borland C++ version 5 is not the same.
Only one difference is "space". Reading from Labview I got "00" (decimal) and reading from Borland C++ I got "32".
I also try to read this binary file with Matlab 6 and I also got "00" as well as those from Labview.
I really struck with this problem.. Anybody has an idea about this problem.
Thanks a lot for anybody help!
NokHi,
These threads regarding reading of binary files was recently discussed in this forum
You might find some answers for your query
http://forums.ni.com/ni/board/message?board.id=170&message.id=99016&requireLogin=False
and
http://forums.ni.com/ni/board/message?board.id=170&message.id=153565&requireLogin=False
Regards
Dev -
Dear All,
I have Binary file. I want to read Bytes based on Patterns and each channel value (Byte values -- > Float conversion) and storing it into Index array.
Please check the attachment for pattren format.
Here, the biggest problem is we will get only pattern style, Based on pattern the data is already stored in Binary file just we need to read it means we need to set the Timestamp based on this.
Please give me some idea to read this kind of pattern files.
BR,
Guru
Munna
Attachments:
Data Reading.xlsx 15 KB
Data Reading.xlsx 15 KBHi Munna,
that pattern is quite hard to understand. It seems there is some information missing…
In your pattern table the data size for e.g. ch1 is given as "1 byte", but in your time schedule you use two bytes for ch1. How are those "ch start position bytes" to be identified?
Byte values -- > Float conversion
How do you want to convert those bytes to Float (SGL or DBL)?
storing it into Index array
What is an "index array"?
It seems you have to create a table from your pattern which identifies the bytes in the file. That seems to be the trickiest part as in your pattern#2 example you already have made a mistake (for ch4 there is no marking at timestamp 70ms)…
Best regards,
GerdW
CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
Kudos are welcome -
Hello All,
Newbie having some trouble with reading a chart from a binary file. My problem may be with trying to use a binary file, I am not sure. The x axis time is not the same length as the actual test time. I have acquired a rms voltage from a VCR RF envelope. I'm using a 6009 DAQ with LV 7.1 on Win2K. I have attached the recording vi and the reading vi and a sample file. I have tried different things including the examples that came with lab view. I need to write a small sized file because this test will last for 4 hours. I have another application that will run for 5 days. I appreciate any help or ideas.
Thanks,
bh3560
Attachments:
Chart write_Read.zip 140 KBHi,
The program you have attached acquires, saves and reads data in ASCII ( floating numbers) and not binary.
To get an idea on how to write and read data in binary format, look at attached examples( taken from examples shipped with labview)
Hope this helps
Regards
Dev
Attachments:
Cont Acq&Graph Voltage-To File(Binary).vi 88 KB
Graph Acquired Binary Data.llb 72 KB -
Hi there,
I'm trying to read a partially binary file with the following structure: The first three lines of the file are regular strings (one can see them correctly when opening the file in a text editor), the rest of the file's contents are integers in their binary form (one cannot see them correctly when opening the file in a text editor).
How can I read such a file?
Thanks in advance!
+P.S.: If you're interested, I'm trying to read a .PPM file (look here to find out about the format).+pfrc wrote:
Hi there,
I'm trying to read a partially binary file with the following structure: The first three lines of the file are regular strings (one can see them correctly when opening the file in a text editor), the rest of the file's contents are integers in their binary form (one cannot see them correctly when opening the file in a text editor).
How can I read such a file?
Thanks in advance!
+P.S.: If you're interested, I'm trying to read a .PPM file (look here to find out about the format).+Use a BufferedInputStream wrapped around a FileInputStream. Read and bytes and until you've hit two end-of-lines, then put those bytes into a String constructor. Note that you'll have to know which line end convention is used, or write your code so as to allow for any of the common ones. After that, continue reading bytes and processing however is appropriate for you. -
Having alot of trouble in file reading in java
i dont know. but i feel really bad that Java is a very good OOP language and i suck big time (not very bad but got frustrated) in reading and writing files. some of the time i have accomplish my task with the help of forums. anyways first i would like to ask 2 questions and then i will state my problem. say for instance if i have a file with name amount and dollars. how can i read it?
i know i can use string regex split method in order to split the line but how can i create a method to do some changes in the text file like i have a name, bank account # and amount to deposit in the text file. my question is how can i declare my method to read (Name) first column and price second column and amount to deposit the third colum?
Secondly if i have a text file and i would like to replace all <<A>> with the name and <<G>> with the age. if i wanted to do without reading a file no problem create a string and then use the replaceAll method ("<<A>>", "Jaan") but for some reason i can't do it when i read a file. yes i am searching on google to get more understanding in reading file. but anyone care to explain wil be great. God bless you my Son.
import java.io.*;
import java.util.*;
class ReadData {
private Scanner s;
private static final String EMPTY_STRING = "";
private String line1;
private static String lineTerminator = System.getProperty("line.separator");
public static void main(String[] args) throws IOException {
ReadData read = new ReadData();
read.start();
public ReadData() {
s = new Scanner(System.in);
public void start() throws FileNotFoundException, IOException {
System.out.println("Enter the file name");
try {
String name = s.next();
openFile(name);
catch (FileNotFoundException e) {
e.printStackTrace();
catch (IOException e) {
e.printStackTrace();
public String openFile(String filename) throws FileNotFoundException, IOException {
String line;
String line2;
StringBuffer document = new StringBuffer(EMPTY_STRING);
File inFile = new File(filename);
FileReader fileReader = new FileReader(inFile);
BufferedReader bufReader = new BufferedReader(fileReader);
while(true) {
line = bufReader.readLine();
if(line==null) break;
document.append(line + lineTerminator);
System.out.print(document.toString());
return document.toString();
}i dont know. but i feel really bad that Java is a
very good OOP language and i suck big time (not very
bad but got frustrated) in reading and writing files.
some of the time i have accomplish my task with the
help of forums. anyways first i would like to ask 2
questions and then i will state my problem. say for
instance if i have a file with name amount and
dollars. how can i read it?Just like you'd read any other file. How you interpret what you've read depends on the specific format of the file, which you've provided no information about.
i know i can use string regex split method in order
to split the line but how can i create a method to do
some changes in the text file like i have a name,
bank account # and amount to deposit in the text
file. my question is how can i declare my method to
read (Name) first column and price second column and
amount to deposit the third colum? What do you mean? You want to read the entire first column, from all lines, then the entire second column, etc.? Unless you know the length of each line ahead of time so you can use RandomAccesFile, you can't do that. If that's not what you mean, then please clarify.
Secondly if i have a text file and i would like to
replace all <<A>> with the name and <<G>> with the
age. if i wanted to do without reading a file no
problem create a string and then use the replaceAll
method ("<<A>>", "Jaan") but for some reason i can't
do it when i read a file.
Create a tmp file.
For each line {
Read a line.
Do the replacement on the string you read.
Write the new line out to the temp file
rename the temp file to the original
anyone care to explain wil be great. God bless you my
Son.I'm not your son. Keep your god away from me. -
Blob for binary file, read/write problems
Hi,
I am relatively new to this type of development so apologies if this question is a bit basic.
I am trying to write a binary document (.doc) to a blob and read it back again, constructing the original word file. I have the following code for reading and writing the file:
private void save_addagreement_Click(object sender, EventArgs e)
// Save the agreement to the database
int test_setting = 0;
// create an OracleConnection object to connect to the
// database and open the connection
string constr;
if (test_setting == 0)
constr = "User Id=royalty;Password=royalty;data source=xe";
else
constr = "User ID=lob_user;Password=lob_password;data source=xe";
OracleConnection myOracleConnection = new OracleConnection(constr);
myOracleConnection.Open();
// create an OracleCommand object to hold a SQL statement
OracleCommand myOracleCommand = myOracleConnection.CreateCommand();
myOracleCommand.CommandText = "insert into blob_content(id, blob_column) values 2, empty_blob())";
OracleDataReader myOracleDataReader = myOracleCommand.ExecuteReader();
// step 2: read the row
OracleTransaction myOracleTransaction = myOracleConnection.BeginTransaction();
myOracleCommand.CommandText =
"SELECT id, blob_column FROM blob_content WHERE id = 2";
myOracleDataReader = myOracleCommand.ExecuteReader();
myOracleDataReader.Read();
Console.WriteLine("myOracleDataReadre[\"id\"] = " + myOracleDataReader["id"]);
OracleBlob myOracleBlob = myOracleDataReader.GetOracleBlobForUpdate(1);
Console.WriteLine("OracleBlob = " + myOracleBlob.Length);
myOracleBlob.Erase();
FileStream fs = new FileStream(agreement_filename.Text, FileMode.Open, FileAccess.Read);
Console.WriteLine("Opened " + agreement_filename.Text + " for reading");
int numBytesRead;
byte[] byteArray = new byte[fs.Length];
numBytesRead = fs.Read(byteArray, 0, (Int32)fs.Length);
Console.WriteLine(numBytesRead + " read from file");
myOracleBlob.Write(byteArray, 0, byteArray.Length);
Console.WriteLine(byteArray.Length + " written to blob object");
Console.WriteLine("Blob Length = " + myOracleBlob.Length);
fs.Close();
myOracleDataReader.Close();
myOracleConnection.Close();
This gives the following console output:
myOracleDataReadre["id"] = 2
OracleBlob = 0
Opened D:\sample_files\oly_in.doc for reading
56832 read from file
56832 written to blob object
Blob Length = 56832
My write to file code is:
private void save_agreement_to_disk_Click(object sender, EventArgs e)
string filename;
SaveFileDialog savedoc = new SaveFileDialog();
if (savedoc.ShowDialog() == DialogResult.OK)
filename = savedoc.FileName;
// create an OracleConnection object to connect to the
// database and open the connection
OracleConnection myOracleConnection = new OracleConnection("User ID=royalty;Password=royalty");
myOracleConnection.Open();
// create an OracleCommand object to hold a SQL statement
OracleCommand myOracleCommand = myOracleConnection.CreateCommand();
myOracleCommand.CommandText =
"SELECT id, blob_column " +
"FROM blob_content " +
"WHERE id = 2";
OracleDataReader myOracleDataReader = myOracleCommand.ExecuteReader();
myOracleDataReader.Read();
Console.WriteLine("myOracleDataReader[id] = " + myOracleDataReader["id"]);
//Step 2: Get the LOB locator
OracleBlob myOracleBlob = myOracleDataReader.GetOracleBlobForUpdate(1);
Console.WriteLine("Blob size = " + myOracleBlob.Length);
//Step 3: get the BLOB data using the read() method
byte[] byteArray = new byte[500];
int numBytesRead;
int totalBytes = 0;
FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write);
while ((numBytesRead = myOracleBlob.Read(byteArray, 0, 500)) > 0)
totalBytes += numBytesRead;
fs.Write(byteArray, 0, byteArray.Length);
Console.WriteLine("numBytes = " + numBytesRead + " totalBytes = " + totalBytes);
Console.WriteLine((int)fs.Length + " bytes written to file");
fs.Close();
myOracleDataReader.Close();
myOracleConnection.Close();
This gives the following console output:
myOracleDataReader[id] = 2
Blob size = 0
0 bytes written to file
If I manually add the blob file using the following:
DECLARE
my_blob BLOB;
BEGIN
-- load the BLOB
my_bfile := BFILENAME('SAMPLE_FILES_DIR', 'binaryContent.doc');
SELECT blob_column
INTO my_blob
FROM blob_content
WHERE id = 1 FOR UPDATE;
DBMS_LOB.FILEOPEN(my_bfile, dbms_lob.file_readonly);
DBMS_LOB.LOADFROMFILE(my_blob, my_bfile, DBMS_LOB.GETLENGTH(my_bfile), 1, 1);
DBMS_LOB.FILECLOSEALL();
COMMIT;
END;
COMMIT;
The write to file works perfectly. This tells me that there must be something wrong with my code that is writing the blob to the database. I tried where possible to following the Oracle article using large objects in .NET but that (along with most things on the internet) focus on uploading text files.
Thanks in advance.
Chris.myOracleCommand.CommandText = "insert into blob_content(id, blob_column) values 2, empty_blob())";
OracleDataReader myOracleDataReader = myOracleCommand.ExecuteReader();
This looks wrong, you shouldn't be using ExecuteReader unless you expect to get a result back. Try using ExecuteNonQuery to do the insert. -
Need a fast ascii file reader in Java
Hi,
My application needs to read around 50000 small ascii (1-25lines) files. Currently I use the BufferedReader API to read ascii files.
Can you suggest something faster than the below.
Thanks
private ArrayList<String> readDataFile(String fileName) {
String lineData;
List<String> fileContents = new ArrayList<String>();
BufferedReader moFile=null;
try {
moFile = new BufferedReader (new FileReader (new File ( fileName)));
while ((lineData = moFile.readLine()) != null)
fileContents.add(lineData);
} catch(IOException e) {
myLogger.error("Exception caught while reading data file: " + fileName + e.toString());
}finally {
try {
moFile.close();
}catch(Exception e) {
//Ignore
return fileContents;
}816417 wrote:
Kayman: I will be using all the contents of the file.Yes, but how? You could speed up the processing by reading all the files into a database once, unless these files are for example created every day and you need to always read the new ones.
I don't have a prototype to provide the absolute time, a jprobe on my application shows that it takes 70% of the time.Yes, but your whole application takes 100% of the time. Do you have reason to believe that 70% is too much of time? What does the other 30% do?
I want to reduce the time spent in this method.You want or you need to? -
How to read a binary file written in LabVIEW 6.1 using VB ?
How to read a file saved in binay forrmat in LabVIEW 6.1 platform through VB.
Is there any code ?
ThanksHello,
LabVIEW files stored in binary can take on just about any format that
you choose, so there will not be a single piece of code that will give
you what you are looking for. You can use VB's standard file
operation functions to read in a binary file created by LabVIEW, just
as you would read in any other binary file. See this page
on Microsoft's web site for more information on the binary file read
operation. How you stored the data in the binary file will
determine how you need to extract it from the byte array. So, if
the first element stored in the file was a 32-bit integer, you could
extract an int from the byte stream to recover that piece of your
data. You would need to know in advance how the file was
formatted in order to successfully retrieve the information. If
you need a reference for the VB functions, the microsoft link above
will get you to some good information.
Cheers,
Matt Pollock
National Instruments -
How can I convert the binary file content to XML message
Dear friends,
I poll the binary file from a ftp server but the payload only includes the binary content, no XML structure in the payload, I hope to convert the binary content to a element node within the XML structure, how can I do that? via content conversion?
Thanks and regards,
BeanRead the binary file stream using java I/O standard functions and convert the read stream to Base64 format. Now map this content to one of the field in target XML structure.
You need a java mapping for this.
what is your target system?
Thanks,
Gujjeti.
Hi Gujjeti,
Thanks a lot for your kind help, my target system is R/3.
Can I achieve that with a UDF or a simple way?
Regards,
Bean -
Binary file transfert over socket : data corupted !
Hi everyone,
I am trying to transfert binary files over Socket (java.net) and I get corrupted data... I know the data I write in the Socket is ok and I wonder why I don't get it right at the end.
Does anyone know about it ?Ok i have re-written it without the Packet class and it know works...
I give my code in case someone would be interested.
ENCODER :
public class Encoder {
// the file to send
private File file;
* Constructor of the Encoder class
* @param path the path to the file to send
public Encoder(String path){
this.file = new File(path);
this.encodeFile();
* This method contains the connection an file tranfert code
private void encodeFile(){
try {
// opening file reading stream
FileInputStream fis = new FileInputStream(this.file);
// connection...
Socket sock = new Socket("127.0.0.1", 5698);
// opening an output stream
BufferedOutputStream bos = new BufferedOutputStream(sock.getOutputStream(), 1024);
// start time
long start = System.currentTimeMillis();
// setting up the buffer
byte[] buffer = new byte[1024];
/* ---- File Transfert Loop ---- */
// reading for the first time
int read = fis.read(buffer);
while (read > 0){
bos.write(buffer);
bos.flush();
read = fis.read(buffer);
/* ----End Of File Transfert ---- */
// end time
long end = System.currentTimeMillis();
// closing streams and connection
fis.close();
bos.close();
sock.close();
// display file transfert duration
System.out.println("Completed in :" + (end - start) + " ms !");
} catch (IOException e) {
e.printStackTrace();
DECODER :
public class Decoder {
private File destFile;
public Decoder(String path){
try {
// setting up destination file
this.destFile = new File(path);
// setting up file writting stream
FileOutputStream fos = new FileOutputStream(this.destFile);
// setting up connection server
ServerSocket serv = new ServerSocket(5698);
// accepting client connection request
Socket sock = serv.accept();
// setting up reading stream for the connection
BufferedInputStream bis = new BufferedInputStream(sock.getInputStream());
// setting up byte buffer
byte[] buffer = new byte[1024];
// first reading
int read = bis.read(buffer);
while (read != -1){
// writting buffer content into file
for (int i=0; i < read; i++){
fos.write(buffer);
// reading next bytes
read = bis.read(buffer);
//closing streams
fos.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
Maybe you are looking for
-
MSS 60.1,What are backend roles required for Manager in Backend
Dear all, I am configuring MSS 60.1.0 with R/3 4.70 and Portal 7.0. Portal user is connected to a PERNR in backend, this PERNR is a chief for a particular org unit. Can some body please suggest me what R/3 roles* I need to assign to PERNR in backend
-
How do I find and agree to the End User License Agreement
I can't download any PDF's, I get a message that says open Adobe Reader and agree to the End User License Agreement. How do I access this??
-
Installing the northbrigde fan
Heyo! I'm finally installed (or tried to) my northbridge fan, but it's not working. It does work, as I attached to my other computer. However, on my board (KT6 Delta LSR) do I have to set it up in the bios? However, I haven't found anywhere to do
-
F.05 tagged to wrong tax code
Hi Gurus, While running F.05, system posted tax code in one of the balance sheet acct is wrong. We're expecting the system to post tax code for revaluation on ac 5304xxxx as G8 or S8 . Pls advise where to make the changes? Regards CL
-
Password no longer works with encrypted disk image.
I have an encrypted disk image on my macbook pro. I enter the password every time I open the disk image. Last week it stopped accepting the password. I checked in keychain where I'd saved the PW when first creating the disk image and verified I was e