How do I convert a big hexadecimal file to a binary file? - java

I Have a text file with the size of 2.4MB
How can I convert it into java?
I use this code but it is not valid:
This initializes the File:
File file = new File("E:/Binary.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
try {
String sCurrentLine;
String bits ="";
br = new BufferedReader(new FileReader("E:/base1.txt"));
while ((sCurrentLine = br.readLine()) != null) {
bits = hexToBin(sCurrentLine);
}
bw.write(bits);
bw.close();
System.out.println("done....");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
This Methods to convert:
static String hexToBin(String s) {
return new BigInteger(s, 16).toString(2);
}

I don't understand what do you mean by a hex file, any file can be read as a binary one and here is an example on how to read & write a binary file:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class BinaryFiles {
public static void main(String... aArgs) throws IOException{
BinaryFiles binary = new BinaryFiles();
byte[] bytes = binary.readBinaryFile(FILE_NAME);
log("size of file read in:" + bytes.length);
binary.writeBinaryFile(bytes, OUTPUT_FILE_NAME);
}
final static String FILE_NAME = "***srcPath***";
final static String OUTPUT_FILE_NAME = "***destPath***";
byte[] readBinaryFile(String aFileName) throws IOException {
Path path = Paths.get(aFileName);
return Files.readAllBytes(path);
}
void writeBinaryFile(byte[] aBytes, String aFileName) throws IOException {
Path path = Paths.get(aFileName);
Files.write(path, aBytes); //creates, overwrites
}
private static void log(Object aMsg){
System.out.println(String.valueOf(aMsg));
}
}
If you want to convert hex to binary use this:
String hexToBinary(String hex) {
int intVal = Integer.parseInt(hex, 16);
String binaryVal = Integer.toBinaryString(intVal);
return binaryVal;
}
You could use the above example to make a combination of converting HEX to binary then writing it.

Related

No output from a program that compiles

I can't wrap my head around why I get zero output... The code looks correct to me, and it compiles with no problem (except for the lack of output). I have tried with absolute path. The text file is stored in the same folder as the class. Am I missing something obvious?
public class File {
public static void main(String[] args) throws FileNotFoundException {
String filename = "./inputD2.txt";
readFile(filename);
System.out.println( readFile(filename));
}
private static List<String> readFile(String filename) {
List<String> records = new ArrayList<>();
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while ((line = reader.readLine()) != null) {
records.add(line);
}
reader.close();
return records;
}
catch (Exception e) {
System.err.format("Exception occurred trying to read '%s'.", filename);
e.printStackTrace();
return null;
}
}
}
package com.test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class FileReaderTest {
public static void main(String[] args) {
String filename = "F:\\Sixth_workspace\\Sampleproject\\src\\main\\resources\\try.txt";
System.out.println("Reading from the text file" + " " + readFile(filename));
}
private static List<String> readFile(String filename) {
List<String> records;
try {
records = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while ((line = reader.readLine()) != null) {
records.add(line);
}
reader.close();
return records;
} catch (Exception e) {
System.err.println("Exception occurred trying to read '%s'." + filename);
e.printStackTrace();
return null;
}
}
}
I modified your code and got the desired output. Use the full path of the text file, here
F:\\Sixth_workspace\\Sampleproject\\src\\main\\resources\\try.txt
is my full path.
Changes:
Changed the classname
Given full path of the text file
Using java 1.8 (above 1.5 is required)

Replace a word in a file with a new file content

I'm writing a code where in data in a file has to be replaced with another file content.
I know how to use a string Replace() function. but the problem here is, I want to replace a string with a entirely new Data.
I'm able to append(in private static void writeDataofFootnotes(File temp, File fout)) the content, but unable to know how do I replace it.
Below is my code.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
public class BottomContent {
public static void main(String[] args) throws Exception {
String input = "C:/Users/u0138039/Desktop/Proview/TEST/Test/src.html";
String fileName = input.substring(input.lastIndexOf("/") + 1);
URL url = new URL("file:///" + input);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
File fout = new File("C:/Users/u0138039/Desktop/TEST/Test/OP/" + fileName);
File temp = new File("C:/Users/u0138039/Desktop/TEST/Test/OP/temp.txt");
if (!fout.exists()) {
fout.createNewFile();
}
if (!temp.exists()) {
temp.createNewFile();
}
FileOutputStream fos = new FileOutputStream(fout);
FileOutputStream tempOs = new FileOutputStream(temp);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
BufferedWriter tempWriter = new BufferedWriter(new OutputStreamWriter(tempOs));
String inputLine;
String footContent = null;
int i = 0;
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("class=\"para\" id=\"")) {
footContent = inputLine.replaceAll(
"<p class=\"para\" id=\"(.*)_(.*)\" style=\"text-indent: (.*)%;\">(.*)(.)(.*)</p>",
"<div class=\"tr_footnote\">\n<div class=\"footnote\">\n<sup><a name=\"ftn.$2\" href=\"#f$2\" class=\"tr_ftn\">$4</a></sup>\n"
+ "<div class=\"para\">" + "$6" + "\n</div>\n</div>\n</div>");
inputLine = inputLine.replaceAll(
"<p class=\"para\" id=\"(.*)_(.*)\" style=\"text-indent: (.*)%;\">(.*)(.)(.*)</p>",
"");
tempWriter.write(footContent);
tempWriter.newLine();
}
inputLine = inputLine.replace("</body>", "<hr/></body>");
bw.write(inputLine);
bw.newLine();
}
tempWriter.close();
bw.close();
in.close();
writeDataofFootnotes(temp, fout);
}
private static void writeDataofFootnotes(File temp, File fout) throws IOException {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader(temp);
fw = new FileWriter(fout, true);
int c = fr.read();
while (c != -1) {
fw.write(c);
c = fr.read();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
close(fr);
close(fw);
}
}
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {
// ...
}
}
}
Here I'm searching for a particular string and saving it in a separate txt file. And once I'm done with the job. I want to replace the <hr /> tag with the entire txt file data.
How can I achieve this?
I'd modify your processing loop as follows:
while ((inputLine = in.readLine()) != null) {
// Stop translation when we reach end of document.
if (inputLine.contains("</body>") {
break;
}
if (inputLine.contains("class=\"para\" id=\"")) {
// No changes in this block
}
bw.write(inputLine);
bw.newLine();
}
// Close temporary file
tempWriter.close();
// Open temporary file, and copy verbatim to output
BufferedReader temp_in = Files.newBufferedReader(temp.toPath());
String footnotes;
while ((footnotes = temp_in.readLine()) != null) {
bw.write(footnotes);
bw.newLine();
}
temp_in.close();
// Finish document
bw.write(inputLine);
bw.newLine();
while ((inputLine = in.readLine()) != null) {
bw.write(inputLine);
bw.newLine();
}
// ... and close all open files

Download a file from MediaFire with Java

As we all know, or might know, MediaFire does not allow direct download links, but you actually have to click the Download button to generate a random link that refers to the file. Is there a way to fetch that link and download it?
In despair of writing an auto-updating application, I have written a short Java application which allows the download of files from MediaFire. Here is the full code:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class mainwindow {
/**
* Launch the application.
*/
static mainwindow thisInstance;
public static void main(String[] args) {
new mainwindow();
}
public mainwindow()
{
otherthread();
}
public void otherthread()
{
navigate("http://www.mediafire.com/download/aqtmhwvb8yvqclu/SmartSharePC.jar","downloadedFromMediafire");
// navigate("http://www.mediafire.com/download/j7e4wh6hbdhdj84/Minecraft+1.5.2-+C.H.T.zip","mediafire");
}
private void navigate(String url,String sufix)
{
try
{
String downloadLink = fetchDownloadLink(getUrlSource(url));
saveUrl(downloadLink,sufix);
} catch (Exception e)
{
e.printStackTrace();
}
}
public void saveUrl(final String urlString,String sufix) throws Exception
{
System.out.println("Downloading...");
String filename = urlString.substring(urlString.lastIndexOf("/")+1, urlString.lastIndexOf("."))+"_"+sufix+urlString.substring(urlString.lastIndexOf("."), urlString.length());
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(urlString).openStream());
fout = new FileOutputStream(filename);
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1)
{
fout.write(data, 0, count);
}
} finally {
if (in != null) {
in.close();
}
if (fout != null) {
fout.close();
}
}
System.out.println("Success!");
}
private static String getUrlSource(String url) throws IOException
{
System.out.println("Connecting...");
URL yahoo = new URL(url);
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream(), "UTF-8"));
String inputLine;
String total="";
while ((inputLine = in.readLine()) != null)
total+=inputLine;
in.close();
return total;
}
private static String fetchDownloadLink(String str)
{
System.out.println("Fetching download link");
try {
String regex = "(?=\\<)|(?<=\\>)";
String data[] = str.split(regex);
String found = "NOTFOUND";
for (String dat : data) {
if (dat.contains("DLP_mOnDownload(this)")) {
found = dat;
break;
}
}
String wentthru = found.substring(found.indexOf("href=\"") + 6);
wentthru = wentthru.substring(0, wentthru.indexOf("\""));
return wentthru;
} catch (Exception e)
{
e.printStackTrace();
return "ERROR";
}
}
}

Making Java I / O and change the file to split in java

I'm making a project where using java I / O
I have a file with the following data:
170631|0645| |002014 | 0713056699|000000278500
155414|0606| |002014 | 0913042385|000001220000
000002|0000|0000|00000000000|0000000000000000|000000299512
and the output I want is as follows:
170631
0645
002014
file so that the data will be decreased down
and this is my source code:
public class Tes {
public static void main(String[] args) throws IOException{
File file;
BufferedReader br =null;
FileOutputStream fop = null;
try {
String content = "";
String s;
file = new File("E:/split/OUT/Berhasil.RPT");
fop = new FileOutputStream(file);
br = new BufferedReader(new FileReader("E:/split/11072014/01434.RPT"));
if (!file.exists()) {
file.createNewFile();
}
while ((s = br.readLine()) != null ) {
for (String retVal : s.split("\\|")) {
String data = content.concat(retVal);
System.out.println(data.trim());
byte[] buffer = data.getBytes();
fop.write(buffer);
fop.flush();
fop.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want is to generate output as above from the data that has been entered
File Input -> Split -> File Output
thanks :)
I think you forgot to mention what problem are you facing. Just by looking at the code it seems like you are closing the fop(FileOutputStream) every time you are looping while writing the split line. The outputStream should be closed once you have written everything, outside the while loop.
import java.io.*;
public class FileReadWrite {
public static void main(String[] args) {
try {
FileReader inputFileReader = new FileReader(new File("E:/split/11072014/01434.RPT"));
FileWriter outputFileWriter = new FileWriter(new File("E:/split/11072014/Berhasil.RPT"));
BufferedReader bufferedReader = new BufferedReader(inputFileReader);
BufferedWriter bufferedWriter = new BufferedWriter(outputFileWriter);
String line;
while ((line = bufferedReader.readLine()) != null) {
for (String splitItem : line.split("|")) {
bufferedWriter.write(splitItem + "\n");
}
}
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Why does the integer written to a file get read as a different value?

I've got a program where I need to generate an integer, write it to a text file and read it back the next time the program runs. After some anomalous behavior, I've stripped it down to setting an integer value, writing it to a file and reading it back for debugging.
totScore, is set to 25 and when I print to the console prior to writing to the file, I see a value of 25. However, when I read the file and print to the console I get three values...25, 13, and 10. Viewing the text file in notepad gives me a character not on the keyboard, so I suspect that the file is being stored in something other that int.
Why do I get different results from my write and read steps?
Is it not being written as an int? How are these values being stored in the file? Do I need to cast the read value as something else and convert it to an integer?
Consider:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.nio.file.*;
import java.nio.file.StandardOpenOption.*;
//
public class HedgeScore {
public static void main(String[] args) {
int totScore = 25;
OutputStream outStream = null; ///write
try {
System.out.println("totscore="+totScore);
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("hedgescore.txt")));
bw.write(totScore);
bw.write(System.getProperty("line.separator"));
bw.flush();
bw.close();
}
catch(IOException f) {
System.out.println(f.getMessage());
}
try {
InputStream input = new FileInputStream("hedgescore.txt");
int data = input.read();
while(data != -1) {
System.out.println("data being read from file :"+ data);
data = input.read();
int prevScore = data;
}
input.close();
}
catch(IOException f) {
System.out.println(f.getMessage());
}
}
}
You're reading/writing Strings and raw data, but not being consistent. Why not instead read in Strings (using a Reader of some sort) and then convert to int by parsing the String? Either that or write out your data as bytes and read it in as bytes -- although that can get quite tricky if the file must deal with different types of data.
So either:
import java.io.*;
public class HedgeScore {
private static final String FILE_PATH = "hedgescore.txt";
public static void main(String[] args) {
int totScore = 25;
BufferedWriter bw = null;
try {
System.out.println("totscore=" + totScore);
bw = new BufferedWriter(new FileWriter(new File(
FILE_PATH)));
bw.write(totScore);
bw.write(System.getProperty("line.separator"));
bw.flush();
} catch (IOException f) {
System.out.println(f.getMessage());
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
InputStream input = null;
try {
input = new FileInputStream(FILE_PATH);
int data = 0;
while ((data = input.read()) != -1) {
System.out.println("data being read from file :" + data);
}
input.close();
} catch (IOException f) {
System.out.println(f.getMessage());
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
or:
import java.io.*;
public class HedgeScore2 {
private static final String FILE_PATH = "hedgescore.txt";
public static void main(String[] args) {
int totScore = 25;
PrintWriter pw = null;
try {
System.out.println("totscore=" + totScore);
pw = new PrintWriter(new FileWriter(new File(FILE_PATH)));
pw.write(String.valueOf(totScore));
pw.write(System.getProperty("line.separator"));
pw.flush();
} catch (IOException f) {
System.out.println(f.getMessage());
} finally {
if (pw != null) {
pw.close();
}
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(FILE_PATH));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException f) {
System.out.println(f.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Categories