How to replace bytes in a file?
How to replace some bytes in a file without rewriting it entirely?
bye
aldo
I repeat my question:I repeat my answer...
java.io.RandomAccessFile.
Have a look at the java doc!
Similar Messages
-
How to convert bytes[] into multipage File object
Hi,
How to convert bytes[] into multipage File object??
I used the java.io.SequenceInputStream to concatenate two input streams (basically .pdf files) into a single input stream. I need to create a single multipage pdf file using this input stream.
Thanks for you help in advance..Only text format allows you to concatenate two files together to get a longer files.
Most formats have a header and a footer and so you cannot simply add one to the other.
You need to use a PDF API which will allow you to build the new document (if one exists) -
How to replace a line in file Java
Hi,
I want to replace a line in file sequencial.
I read file, but i don't know how to replace one line..
Thanks...I supose this..
I usea a FileReader and BufferedReader to read a file.
I read a line, I know the number of the line, but how to say to method println o write what it's the line to replace? -
How to replace a string in file
if a file's content is:
aaa 123 456
bbb 341 343
ccc 343 233
now i want to replace 341 with 768
how?
& use which classes? thx!I would suggest
java.io*;
Use a beffered Reader, read the file, and output into another one -
Hi everyone,
I have a txt file and It has some data's. I want to specifically replace a character in the text file. Data's will be like this,
TT=15
S1ST=21601
S1EN=50400
S2ST=50401
S2EN=72000
S3ST=72001
S3EN=21600
GNST=00000
GNEN=00000
S1B1S=22800
S1B1E=23400
S1B2S=28800
S1B2E=30600
S1B3S=36000
S1B3E=36600
S1B4S=45000
S1B4E=46800
In the 2nd line i.e. S1ST=21601, I want to replace 36000 instead of 21601.
After replacing the specific character, data's should overwrite in the file or appending the file will also ok for me.
Give me a suggestion. I am using LV 8.2. So plz post your code in 8.2 ver
Thanks in advance.
Regards,
Vijay
Solved!
Go to Solution.Check this out.
Edit:- attaching 8.2 version
With Regards
Miraz
Kudos is better option to thank somebody on this forum
Attachments:
String.vi 8 KB
String.vi 8 KB -
How to sync writing to a file?
Hi all,
I'm implementing a simple line logger for my web applications.
Basically, I have some class with a "write" method, that appends a line of text into a certain file.
All of my web apps log into the same file (by design).
How do I make sure writing to the file is synchronized?
The web apps cannot share logger objects between them (not even singletons, correct?) so using the 'synchronized' qualifier for the 'write' method won't work because each web app has its own instance of the logger object.
Also, FileLock won't work since all web apps "live" inside the same JVM (accoding to javadoc, FileLock is not suitable for syncing file-writes by different threads within the same JVM).
I've looked up the forum for answers to these questions, but non of the threads on this topic provided any leads...
Any ideas?hii...
can sum1 plz tell me how to replace bytes in a file?
i've used randomaccess to open the file....read is
contents and write back to it at the desired
locations using seek()...however at some position if
i wish to read the data and replace it with new data
at exactly the same location...how can i do it??
bye.i had already mentioned my problem....actually i want to read a record from a file and then update it at the same location in the file...so i need to replace it(or delete the record and re-write the new info). -
How to convert bytes[] into File object
hi
how to convert byte array into File object
pls.. help me
Regards
srinurrrr007 wrote:
Hi,
How to convert bytes[] into multipage File object?? ]There's no such thing as a "multipage File object." You ought to re-read this thread closely, and read the [API docs for File|http://java.sun.com/javase/6/docs/api/java/io/File.html] to clear up your confusion about what a File object is.
I used the java.io.SequenceInputStream to concatenate two input streams (basically .pdf files) into a single input stream. I need to create a single multipage pdf file using this input stream. Then you need a pdf API, like iText or fop. You can't just concatenate pdf files, word docs, excel sheets, etc., like you can text files. Google for java pdf api. -
How to replace or remove last 500 bytes of a file without rewriting all the file?
Hi everyone,
Usually I only ask for help when I can't find a solution for several days or weeks... And guess what? That just happen!
So, this is what i am trying to do:
I have a program to ZIP folder and protect them with password, then it encrypts the zip file.
That it's working fine, until the user forgets his password.
So, what I want to do is give the user a Recovery Password option for each ZIP file created. I can't use the Windows Registry because the idea is to be able to recover the password in any computer.So i came up with an idea...
In simple terms, this will work like this:
0 - Choose folder to ZIP
1 - Ask user for recover details (date of birth, email etc)
2 - ZIP folder with password
3 - Encrypt ZIP file
4 - Encrypt recover details and convert it to HEX
5 - Add recover details (in HEX) to the end of the ZIP file (last bytes)
6 - Add "5265636F76657244657461696C73" which is the text "RecoverDetails" in HEX
7 - Add "504B0506000000000000000000000000000000000000" this is the final bytes of a ZIP file and will make the Operating System think that is a ZIP file (i know that will give an error when we try to open it.. the ideia is to change the
extension later and use my software to do all the work to access this ZIP/folder again)
So, explaining what it's here, I want to say that I managed how to do all of this so far. The point number 6 will help us to determine where the recover details are in the file, or if they actually exist because user can choose not to use them.
In order to unlock this ZIP and extract it's contents, I need to reverse what I've done. That means, that need to read only the last 500 bytes (or less if the file is smaller) of the ZIP and remove those extra bytes I added so the program can check
if the user is inputing a correct password, and if so decrypt contents and extract them.
But, if the user insert a wrong password I need to re-add those bytes with the recover details again to the ZIP file.
The second thing is, if the user forgets his password and asks to recover it, a form will be shown asking to insert the recover detail (date of birth, email etc), so we need to reed the last 500 bytes of the ZIP, find the bytes in number 6 and remove the
bytes before number 6, remove bytes in number 6 and number 7, and we will have the recover details to match against the user details input.
I have all done so far with the locking process. But i need help with the unlocking.
I am not sure if it's possible, but this what i am looking for:
Read last 500 bytes of a file, remove the bytes with recover details and save the file. Without reading the whole file, because if we have a 1GB file that will take a very long time. Also, i don't want to "waste" hard drive space creating a new
clone file with 1GB and then delete the original.
And then add them back "in case user fails the password" which should be exactly the same.
This sounds a bit confusing I know, even to me, I am writing and trying to explain this the better I can.. Also my English is not the best..
Here it goes some code to better understanding:
'READ LAST 500 BYTES OF ZIP FILE TO CHECK IF IT CONTAINS RECOVER DETAILS
Dim oFileStream As New FileStream(TextBox_ZIP_to_Protect.Text & ".zip", FileMode.Open, FileAccess.Read)
Dim oBinaryReader As New BinaryReader(oFileStream)
Dim lBytes As Long = oFileStream.Length
oBinaryReader.BaseStream.Position = lBytes - 500
Dim fileData As Byte() = oBinaryReader.ReadBytes(500)
oBinaryReader.Close()
oFileStream.Close()
Dim txtTemp As New System.Text.StringBuilder()
For Each myByte As Byte In fileData
txtTemp.Append(myByte.ToString("X2"))
Next
Dim RecoveryDetailsPass_Holder = txtTemp.ToString()
'Dim Temp_2 = txtTemp.ToString()
'RichTextBox1.Text = txtTemp.ToString()
If txtTemp.ToString.Contains("505245434F47414653") Then
'we have password recovery details(the numbers mean RecoverDetails in HEX)
'next we will get rid of everything before and after of string "cut_at"
Dim mystr As String = RecoveryDetailsPass_Holder 'RichTextBox1.Text
Dim cut_at As String = "505245434F47414653"
Dim x As Integer = InStr(mystr, cut_at)
' Dim string_before As String = mystr.Substring(0, x - 1)
Dim string_after As String = mystr.Substring(x + cut_at.Length - 1)
RecoveryDetailsPass_Holder = RecoveryDetailsPass_Holder.Replace(string_after.ToString, "")
RecoveryDetailsPass_Holder = RecoveryDetailsPass_Holder.Replace("505245434F47414653", "") ' this is RecoverDetails in HEX
RecoveryDetailsPass_Holder = RecoveryDetailsPass_Holder.Replace("504B0506000000000000000000000000000000000000", "") ' this is the bytes of an empty zip file
'AT THIS POINT WE HAVE ONLY THE RECOVER PASSWORD DETAILS (date of birth, email etc) IN THE VARIABLE "RecoveryDetailsPass_Holder"
'////////////////////////////////////////////////////// TO DEBUG
'MsgBox(string_after.ToString & "505245434F47414653")
'InputBox("", "", string_after.ToString)
'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ TO DEBUG
'Temp_2 = Temp_2.Replace(RecoveryDetailsPass_Holder.ToString, "")
Now that we have the recover details, we need to remove them from ZIP in order to the software try to unzip it with the password provided by the user on the GUI.
If the user needs to recover the password we have the details already in RecoveryDetailsPass_Holder variable and just need to match them against user input details.
If the user fails, we need to put the RecoveryDetailsPass_Holder back on the file.
Any question just ask, it's a bit trick to explain i think, but please ask.
Anyone know how to do this?
Many thanks in advanced.
Nothing is impossible!
@ Portugal
Vote if it's helpfull :)@ ALL
Thank you very much for you help. I know that if I'm "playing" with bytes you should assume that I know a lot of VB.net, but I don't know that much unfortunately. I am not a beginner but I am still very fresh and I probably do stuff that work but
probably not in the best way...
Anyway, I will explain the idea of this little software I'm making. Once I wanted to create a program to protect folders with password, and I came up with something to change folder permissions to lock access to them, and that actually worked fine and quickly.
However, I managed how to "crack" the protection by going to folder properties, security tab and then give permissions back to my username. So that, to me, wasn't a safer system to protect folders, also I want the ability to use passwords. So I search
and search online for a way to do it, and someone replied (to someone with the same question as me) that the best option would be to create a zip with all contents of the folder, with password and then change the extension from .zip to .whatever and register
the new extension .whatever on the Windows Registry, so that file will have an icon and open with my software.
So I did...The program zips everything, change the extension and I added the encryption to avoid people changing the extension to ZIP or trying to open with 7-Zip or similar and be able to see the protected files names in the .zip/.whatever
Answering to all of you now:
@Armi
"System.IO.FileStream.SetLength"
I know I tried that but I erased the code because it didn't work for some reason, I don't remember why sorry, was long time before I created this post.
The last code I was trying to use was this:
' Set the stream position to the desired location of the stream.
Dim fileStream As IO.FileStream = _
New IO.FileStream(TextBox_ZIP_to_Protect.Text & ".zip", IO.FileMode.Append)
Try
' Set the stream (OFFSET) position to the desired location of the stream.
fileStream.Seek(210, IO.SeekOrigin.Current)
Dim Bytes_do_ZE As Byte() = HexStringToByteArray(Temp_2.ToString)
'Write Characters ASCII
For Each Byte_Do_Zeca As Byte In Bytes_do_ZE
fileStream.WriteByte(Byte_Do_Zeca)
Next
Finally
fileStream.Close()
End Try
and we need this:
Private Shared Function HexStringToByteArray(ByRef strInput As String) As Byte()
Dim length As Integer
Dim bOutput As Byte()
Dim c(1) As Integer
length = strInput.Length / 2
ReDim bOutput(length - 1)
For i As Integer = 0 To (length - 1)
For j As Integer = 0 To 1
c(j) = Asc(strInput.Chars(i * 2 + j))
If ((c(j) >= Asc("0")) And (c(j) <= Asc("9"))) Then
c(j) = c(j) - Asc("0")
ElseIf ((c(j) >= Asc("A")) And (c(j) <= Asc("F"))) Then
c(j) = c(j) - Asc("A") + &HA
ElseIf ((c(j) >= Asc("a")) And (c(j) <= Asc("f"))) Then
c(j) = c(j) - Asc("a") + &HA
End If
Next j
bOutput(i) = (c(0) * &H10 + c(1))
Next i
Return (bOutput)
End Function
That code, as I understand, is to search for the OFFSET of the bytes in the file and start to write from there... That OFFSET should be the beginning of the 500 bytes read on the code before. I got the OFFSET position "210" reading the file with
the HEX editor "HxD - Hexeditor v1.7.7.0" but using the OFFSET won't work because every file, password, recover details and so on, are different and so the file size, changing the OFFSET I
think.
@Reed Kimble
Does that sound like something which might work for you?
Thanks for your help. That might be some solution, however it seams a bit of the same problem where we need to read the bytes again to get the recover details. But, as I said in this post, because this is meant to password protect folders, do you think that
will apply as well?
@Crazypennie
Thanks for your reply.
All this appears really weak. The user has your application since he need it to open the file .... and the code in the application contain the code to read the file without knowing the password. Therefore anyone can read your code and retrieve the
data without the password ... if he knows VB.
The application can only open the file if the user didn't use a password to protect the file. Because the file is encrypted and needs to be unencrypted first.
When the application tries to open/read the file, will need to decrypt it first and then check for a password and do the validation. Also the application is with the code masked/protected which i think it might not be easy for reverse engineering.
- You need to use a web server and a symmetric key encryption
This a good idea, besides I don't know how to implement it. However the idea is to be able to:
1 - Protect a folder anywhere in any Windows computer (portable app)
2 - Recover password details (security question) in any computer, online and offline
And I think we need a computer always connected to the Internet to use that method, right?
@ Mr. Monkeyboy
Thank you very much for your effort.
I just wanted to let you know that the zip method you are using is no longer supported.
I didn't actually knew that. Thanks for letting me know.
Do you require the compressed encrypted files to actually be Zip files or could they just be compressed files that have nothing to do with Zip?
No, it doesn't need to be a .zip extension. I am actually using my own extension. It starts as a Zip but then I changed to my own extension which I have registered on the Windows Registry.
@ ALL
Thanks again to all for trying and spending time helping me.
By the way, I might not be able to answer or try any code during the weekend... It's easter break and family is around. Have a nice easter everyone. :)
Nothing is impossible! Imagination is the limit! -
How can I replace an older save file with a new one on game center?
Greetings,
I have been trying to change an older game saved file that I have created with my old Ipad with the new one that I have created on my new Ipad, both game files are played under my apple ID but I have no idea how to replace my older one with the new one.
The new file is superior to the old one so I wish to add the new saved file to my game center.
The game I am playing is Clash of Clans both file are created on apple products.
Let me know if there is a sulotion for that case.
RegardsMake sure the site folder created by iWeb is named exactly the same as the site folder currently on the server.
OT -
How to replace the string in a file
Hi, I have a file which contains the following data
File.dat
<file>
<filenum>
W10
</filenum>
<hello>Heading </hello>
</file>
I need to replace the contents of file.dat
database sequence value (for example xx_seq.nextval)
Can some one please tell me how to search this <filenum>
W10</filenum>
and replace this with xx_seq.nextval
and write the entire contents of the file to new file
I am doing some thing like this
suppose if my database value returns 11 from the above sequence then
the output should be in file2.dat as
<file>
<filenum>
11</filenum>
<hello>Heading </hello>
</file>
declare f_in utl_file.file_type;
s_in varchar2(10000);
string1 varchar2(32000);
x number;
begin
f_in := utl_file.fopen('SAMPLEDIR','input.txt','R');
f_in1 := utl_file.fopen('SAMPLEDIR','input1.txt','W');
select xx_seq.nextval into x from dual;
loop
begin utl_file.get_line(f_in,s_in);
EXCEPTION
WHEN NO_DATA_FOUND THEN
EXIT;
string1:= string1 || s_in;
utl_file.put_line( (f_in1,s_in);
end;
end loop;
utl_file.fclose(f_in);
end;
In this case it is reading and writing as it is, but unable to replace the sequence value
Can some one please tell me how to do using replace function
ThanksHi, I have tried this but getting error
step 1: create table test_dept(dno number, dname varchar2(20))
insert into test_dept values(10,'10-Sourcing dept');
insert into test_dept values(20,'20-Audting dept');
insert into test_dept values(30,'30-Computer dept');
select * from test_dept;
DNO DNaME
10 10-Sourcing dept
30 30-Computer dept
20 20-Audting dept
step 2:
create table test_web (name varchar2(60), xml_col xmltype) ;
step 3:
create sequence test1_seq start with 100 increment by 1
step 4:
test.out has the following contents (it is not .xml file) and i dont have <?xml version="1.0" ?> tag at the begining
<File>
<File_Type>Type1</File_Type>
<File_Header_Record>
<file_num>WP10</file_num>
</File_Header_Record>
<Transaction>
<Transaction_Type>TR 1</Transaction_Type>
<Amount>
<Amounts>100</Amounts>
</Amount>
<Depts>
<Dept_Type>Sourcing</Dept_Type>
<Dept>10</Dept>
</Depts>
</Transaction>
<Transaction>
<Transaction_Type>TR 2</Transaction_Type>
<Amount>
<Amounts>200</Amounts>
</Amount>
<Depts>
<Dept_Type>Auditing</Dept_Type>
<Dept>20</Dept>
</Depts>
</Transaction>
<Transaction>
<Transaction_Type>TR 3</Transaction_Type>
<Amount>
<Amounts>300</Amounts>
</Amount>
<Depts>
<Dept_Type>Computer</Dept_Type>
<Dept>30</Dept>
</Depts>
</Transaction>
</File>
step 5:
DECLARE
v_check_file_exist BOOLEAN;
v_file_length NUMBER;
v_block_size NUMBER;
v_file_path VARCHAR2 (100);
v_file_name VARCHAR2 (100);
v_file_type UTL_FILE.FILE_TYPE;
v_str varchar2 (32760);
v_cnt number;
v_seq number;
--check whether file exists and has data in it
BEGIN
v_file_path := '/usr/tmp';
v_file_name := 'test.xml.out';
-- initailise the variables
v_cnt := 0;
UTL_FILE.FGETATTR (v_file_path,
v_file_name,
v_check_file_exist,
v_file_length,
v_block_size);
if v_check_file_exist
then
DBMS_OUTPUT.put_line (' File exists');
IF v_file_length > 0 AND v_block_size > 0
THEN
BEGIN
select test1_seq.nextval into v_seq from dual;
insert into test_web values(v_seq,v_file_name);
EXCEPTION
WHEN NO_DATA_FOUND
THEN
DBMS_OUTPUT.put_line ('No data found '||SQLERRM);
WHEN OTHERS
THEN
DBMS_OUTPUT.put_line ('others '||SQLERRM);
END;
commit;
ELSE
DBMS_OUTPUT.put_line ('No Data in File');
END IF;
ELSE
DBMS_OUTPUT.put_line (' File Not Available');
END IF;
END;
I am getting below error
File exists
others ORA-31011: XML parsing failed
ORA-19202: Error occurred in XML
processing
LPX-00210: expected '<' instead of 't'
Error at line 1
My requirement is to replace the
1. contents of the file WP10 from <file_num>WP10</file_num>
with sequence value 'WP101' because sequence is starting at 100
2. Replace all Dept tag <Dept>30</Dept> with Dname value from test_dept table
for example
<Dept>10</Dept> should be replaced with <Dept>10-Sourcing dept</Dept>
update the
when i say select * from test_web;
It should contain this row
101 <File>
<File_Type>Type1</File_Type>
<File_Header_Record>
<file_num>WP101</file_num>
</File_Header_Record>
<Transaction>
<Transaction_Type>TR 1</Transaction_Type>
<Amount>
<Amounts>100</Amounts>
</Amount>
<Depts>
<Dept_Type>Sourcing</Dept_Type>
<Dept>10-Sourcing dept</Dept>
</Depts>
</Transaction>
<Transaction>
<Transaction_Type>TR 2</Transaction_Type>
<Amount>
<Amounts>200</Amounts>
</Amount>
<Depts>
<Dept_Type>Auditing</Dept_Type>
<Dept>20-Audting dept</Dept>
</Depts>
</Transaction>
<Transaction>
<Transaction_Type>TR 3</Transaction_Type>
<Amount>
<Amounts>300</Amounts>
</Amount>
<Depts>
<Dept_Type>Computer</Dept_Type>
<Dept>30-Computer dept</Dept>
</Depts>
</Transaction>
</File>
Can you please check
Thanks -
How to get the file size (in bytes) for all files in a directory?
How to get the file size (in bytes) for all files in a directory?
The following code does not work. isFile() does NOT recognize files as files but only as directories. Why?
Furthermore the size is not retrieved correctly.
How do I have to code it otherwise? Is there a way of not converting f-to-string-to-File again but iterate over all file objects instead?
Thank you
Peter
java.io.File f = new java.io.File("D:/todo/");
files = f.list();
for (int i = 0; i < files.length; i++) {
System.out.println("fn=" + files);
if (new File(files[i]).isFile())
System.out.println("file[" + i + "]=" + files[i] + " size=" + (new File(files[i])).length() ); }pstein wrote:
...The following code does not work. Work?! It does not even compile! Please consider posting code in the form of an SSCCE in future.
Here is an SSCCE.
import java.io.File;
class ListFiles {
public static void main(String[] args) {
java.io.File f = new java.io.File("/media/disk");
// provides only the file names, not the path/name!
//String[] files = f.list();
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println("fn=" + files);
if (files[i].isFile()) {
System.out.println(
"file[" +
i +
"]=" +
files[i] +
" size=" +
(files[i]).length() );
}Edit 1:
Also, in future, when posting code, code snippets, HTML/XML or input/output, please use the code tags to retain the indentation and formatting. To do that, select the code and click the CODE button seen on the Plain Text tab of the message posting form. It took me longer to clean up that code and turn it into an SSCCE, than it took to +solve the problem.+
Edited by: AndrewThompson64 on Jul 21, 2009 8:47 AM -
How to replace a line ina text file using java?
Hi ALL,
Does anybody know how to replace a line in a text file uisng java.use this thing:
http://doesthatevencompile.com/current-projects/code-sniplets/ASCIIFile.htm
open the file,
read its contents, replace the text you need in the contents, set the contents back into the file.
it takes care of the IO for you. -
i wrote a assignment of almost 2500 words in the microsoft word 97-2003 doc but by mistake replace a table only in same name . how can i retain my orinal file which was as Basel III and Banking law
Hey Christian
Thanks I havn't seen that post, busy trying it now but no luck so far.
I defined it in the second one (Content Management - Utilities - MIME Types).
Tried it now in NWA, no luck either . . .
What I noticed is no matted what it is defined as in NWA or Content Management, the properties of the mht file still shows Binary File (application/octet-stream)
Any ideas?
Regards
Antonette -
I wrote an 2500 words assignment and saved in Microsoft word 97-2003 and by mistake replaced with another word file.How can i retain my original work?
Hi,
Does this happen to all 97-2003 Word files?
Word 2013 now has lots of updates compared with earlier version of Word, lots of features have been updated. Use Word 2013 to open documents created in earlier versions of Word (Word 97-2003 format), you will probably encounter unexpected problems,
expecially for those heavily formatted files.
We would suggest you to convert your document to the Word 2013 file format, then you will be able to access the new and enhanced features in Word 2013.
Regards,
Ethan Hua
TechNet Community Support
It's recommended to download and install
Configuration Analyzer Tool (OffCAT), which is developed by Microsoft Support teams. Once the tool is installed, you can run it at any time to scan for hundreds of known issues in Office
programs. -
How do I transfer larger PDF files stored in iBooks to replacement iPad?
How do I transfer larger PDF files stored in iBooks to replacement iPad?
Do you sync with iTunes and are the PDF files in your iTunes library? If they are, sync the iPad with iTunes.
Maybe you are looking for
-
Adobe Captivate 7 Installing Problem
I purchased the Adobe Captivate 7 software on Feb 4 through Adobe website. As there were some issues on my computer yesterday, I uninstalled Captivate 7. But today, when I tried to download the software again and reinstall it, it did not work. After
-
Videos will not play in Safari
I have an iPhone 3GS on the 3.1.2 OS, and cannot get videos to play in Safari. I've tried watching videos on ESPN's mobile site, as well as the TV Ads for the iPhone on Apple's website, and all that shows up is a screen full of code. Any assistance i
-
I'm running a program with selenium and it was working fine, then I updated to firefox version 22 and now its throwing my error saying 3rd party cookies need to be enabled. Is there a line of code I can add to prefs.js in order to ensure that 3rd par
-
Hi all, Has any one done something like in Segment Values screen -> Key flexfield -> Title: Territory flexfield -> Value, Country -> Values, Effective Currently there is a Value = 190 and Description = Malaysia. I would want to update All Tables (all
-
CAnt hear Siri when using microphone headphones. She can hear me when using them; i tried another pair, and same thing. I can hear her when using regular headphones, though. Anybody have a suggestion?