Why doesn't it read the line-termination ''\n' - java

This code is trying to read a file then reverse it to an output file.
When it writes it (without reversing) the output is the same.
But when it is reversed the output is written ALL on ONE line in the output file.
int i;
int x = 0;
int[] ar = new int[9999];
BufferedInputStream fin;
BufferedOutputStream fout;
try {
File f1 = new File("C:/Users/NetBeansProjects/QuestionOne/input.txt");
File f2 = new File("C:/Users/NetBeansProjects/QuestionOne/output.txt");
fin = new BufferedInputStream(new FileInputStream(f1));
fout = new BufferedOutputStream(new FileOutputStream(f2));
while ((i = fin.read()) != -1) { //reads file into an array
ar[x] = i;
x++;
}
for(int y = (x-1); y >= 0; y--){
//writes to a file from the end of the array
fout.write(ar[y]);
}
System.out.println();
fin.close();
fout.close();
} catch (FileNotFoundException e) {
System.out.println("File is NOT found.");
}
I'm using BufferedInputStream and BufferedOutputStream

Probably you are reading \r\n and writing back \n\r.
You have to handle \r\n as a separate entity.

Related

Converting Binary PGM Files to ASCII PGM Files using Java? Using FileWriter gives empty file

How can I convert Binary PGM Files to ASCII PGM Files using Java?
When I use the following code, I am unable to write ASCII values in the B.pgm. I've tried using dos.writeInt also.
FileInputStream inRaw = null;
FileOutputStream outRaw = null;
try {
inRaw = new FileInputStream("A.pgm");
outRaw = new FileOutputStream("B.pgm");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
DataInputStream dis = new DataInputStream(inRaw);
DataOutputStream dos = new DataOutputStream(outRaw);
int i = 0;
String temp = null;
temp = dis.readLine();
System.out.println(temp);
dos.writeBytes("P2");
dos.writeBytes("\n");
while(i < 3){
temp = dis.readLine();
System.out.println(temp);
dos.writeBytes(temp);
dos.writeBytes("\n");
i++;
}
int t = 0;
while(dis.available() != 0){
t = dis.read();
System.out.println(t);
fileWriter.write(t);
dos.writeInt(t);
dos.writeBytes("\n");
}
dis.close();
dos.close();
I tried to use FileWriter instead of DataOutputStream and the code produces an empty file, I can't figure out why?
FileInputStream inRaw = null;
FileOutputStream outRaw = null;
try {
inRaw = new FileInputStream("A.pgm");
outRaw = new FileOutputStream("B.pgm");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
DataInputStream dis = new DataInputStream(inRaw);
FileWriter fileWriter = new FileWriter("B.pgm");
int i = 0;
String temp = null;
temp = dis.readLine();
System.out.println(temp);
fileWriter.write("P2");
fileWriter.write("\n");
while(i < 3){
temp = dis.readLine();
System.out.println(temp);
fileWriter.write(temp);
fileWriter.write("\n");
i++;
}
int t = 0;
while(dis.available() != 0){
t = dis.read();
System.out.println(t);
fileWriter.write(t);
fileWriter.write(t);
fileWriter.write("\n");
}
dis.close();
(This might not solve your issue, but it will make your code much more robust).
One of the possible reasons why data isn't written to a file is that you don't actually close the stream - it can be held in an in-memory buffer until then, and is never written out. You certainly don't make an explicit call to fileWriter.close().
You can try to close the streams manually, but it's normally unnecessary, and surprisingly tricky to do it correctly in all circumstances.
It is easier to use try-with-resources - this automatically manages your streams, and guarantees they are closed by the end of the block.
try (FileInputStream inRaw = new FileInputStream("A.pgm");
FileOutputStream outRaw = new FileOutputStream("B.pgm");
DataInputStream dis = new DataInputStream(inRaw);
DataOutputStream dos = new DataOutputStream(outRaw)) {
// The logic to read dis and write it to dos.
} catch (IOException e) {
e.printStackTrace();
}
// No need to close the streams - that happened automatically.
You can do similarly with the second version by substituting the FileWriter fileWriter = new FileWriter(outRaw) for DataOutputStream dos = ....
If this doesn't solve the immediate issue, I would suggest that there is an error in your logic. Try stepping through the code with a debugger - make sure that the write calls are actually being performed.

Reading JPEG Stream over socket gives Null characters

I am reading a .jpg file over InputStream using this code but I am receiving NULNUL...n stream after some text. Ii am reading this file link to file and link of file that I received , link is Written File link.
while ((ret = input.read(imageCharArray)) != -1) {
packet.append(new String(imageCharArray, 0, ret));
totRead += ret;
imageCharArray = new char[4096];
}
file = new File(
Environment.getExternalStorageDirectory()
+ "/FileName_/"
+ m_httpParser.filename + ".jpg");
PrintWriter printWriter = new PrintWriter(file);
// outputStream = new FileOutputStream(file); //also Used FileoutputStream for writting
// outputStream.write(packet.toString().getBytes());//
// ,
printWriter.write(packet.toString());
// outputStream.close();
printWriter.close();
}
I have also tried FileoutputStream but hardlucj for this too as commented in my code.
Edit
I have used this also. I have a content length field upto which i am reading and writing
byte[] bytes = new byte[1024];
int totalReadLength = 0;
// read untill we have bytes
while ((read = inputStream.read(bytes)) != -1
&& contentLength >= (totalReadLength)) {
outputStream.write(bytes, 0, read);
totalReadLength += read;
System.out.println(" read size ======= "
+ read + " totalReadLength = "
+ totalReadLength);
}
String is not a container for binary data, and PrintWriter isn't a way to write it. Get rid of all, all, the conversions between bytes and String and vice versa, and just transfer the bytes with input and output streams:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
If you need to constrain the number of bytes read from the input, you have to do that before calling read(), and you also have to constrain the read() correctly:
while (total < length && (count = in.read(buffer, 0, length-total > buffer.length ? buffer.length: (int)(length-total))) > 0)
{
total += count;
out.write(buffer, 0, count);
}
I tested it in my Nexus4 and it's working for me. Here is the snippet of code what I tried :
public void saveImage(String urlPath)throws Exception{
String fileName = "kumar.jpg";
File folder = new File("/sdcard/MyImages/");
// have the object build the directory structure, if needed.
folder.mkdirs();
final File output = new File(folder,
fileName);
if (output.exists()) {
output.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
// InputStreamReader reader = new InputStreamReader(stream);
DataInputStream dis = new DataInputStream(url.openConnection().getInputStream());
byte[] fileData = new byte[url.openConnection().getContentLength()];
for (int x = 0; x < fileData.length; x++) { // fill byte array with bytes from the data input stream
fileData[x] = dis.readByte();
}
dis.close();
fos = new FileOutputStream(output.getPath());
fos.write(fileData);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Just Call the above function in a background thread and pass your url. It'll work for sure. Let me know if it helps.
You can check below code.
destinationFile = new File(
Environment.getExternalStorageDirectory()
+ "/FileName_/"
+ m_httpParser.filename + ".jpg");
BufferedOutputStream buffer = new BufferedOutputStream(new FileOutputStream(destinationFile));
byte byt[] = new byte[1024];
int i;
for (long l = 0L; (i = input.read(byt)) != -1; l += i ) {
buffer.write(byt, 0, i);
}
buffer.close();

PDF to Bytearray conversion in java

Below is my code to convert a PDF file to byte array
public class ByteArrayExample{
public static void main(String[] args) {
try{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter File name: ");
String str = bf.readLine();
File file = new File(str);
//File length
int size = (int)file.length();
if (size > Integer.MAX_VALUE){
System.out.println("File is to larger");
}
byte[] bytes = new byte[size];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
int read = 0;
int numRead = 0;
while (read < bytes.length && (numRead=dis.read(bytes, read,
bytes.length-read)) >= 0) {
read = read + numRead;
}
System.out.println("File size: " + read);
// Ensure all the bytes have been read in
if (read < bytes.length) {
System.out.println("Could not completely read: "+file.getName());
}
}
catch (Exception e){
e.getMessage();
}
}
}
Issue is this actually converts the file name into the byte array not the actual PDF file.Can anyone please help me with this.
I added this to the end to check it and it copied the PDF file. Your code is working fine
dis.close();
DataOutputStream out = new DataOutputStream(new FileOutputStream(new File("c:\\out.pdf")));
out.write(bytes);
out.close();
System.out.println("File size: " + read);
// Ensure all the bytes have been read in
if (read < bytes.length) {
System.out.println("Could not completely read: "+file.getName());
}
edit: here is my entire code, its just copied from yours. I ran it in IDE (eclipse) and entered "c:\mypdf.pdf" for the input and it copied it to out.pdf. Identical Copys. Do note that I did close both streams which I noticed you forgot to do in your code.
public class Main {
public static void main(String[] args) {
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter File name: ");
String str = bf.readLine();
File file = new File(str);
//File length
int size = (int) file.length();
if (size > Integer.MAX_VALUE) {
System.out.println("File is to larger");
}
byte[] bytes = new byte[size];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
int read = 0;
int numRead = 0;
while (read < bytes.length && (numRead = dis.read(bytes, read,
bytes.length - read)) >= 0) {
read = read + numRead;
}
dis.close();
DataOutputStream out = new DataOutputStream(new FileOutputStream(new File("c:\\out.pdf")));
out.write(bytes);
out.close();
System.out.println("File size: " + read);
// Ensure all the bytes have been read in
if (read < bytes.length) {
System.out.println("Could not completely read: " + file.getName());
}
} catch (Exception e) {
e.getMessage();
}
}
}

How to save files over socket into list

I have a method that works perfectly, but instead of having it write to a file, how do I have it add each line of the file to a list? (Some files are .docx and some are .txt)
private static void saveMultiple(Socket socket) {
try {
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
DataInputStream dis = new DataInputStream(bis);
int filesCount = dis.readInt();
File[] files = new File[filesCount];
for (int i = 0; i < filesCount; i++) {
long fileLength = dis.readLong();
String fileName = dis.readUTF();
files[i] = new File("/Users/.../Desktop/Data/" + fileName);
FileOutputStream fos = new FileOutputStream(files[i]);
BufferedOutputStream bos = new BufferedOutputStream(fos);
for (int x = 0; x < fileLength; x++) {
bos.write(bis.read());
}
bos.close();
}
dis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
This part of you code:
bos.write(bis.read());
Basically read 1 byte from the socket and writes it into file. Now instead of doing this, you can buffer the bytes into a byte array, and use java.util.String String(byte[] bytes) constructor to turn it into a String. Consider using ByteInputStream.read(byte[] b, int off, int len) method.
You have to take into account the character encoding and memory consumption too.

Joining two mp3 files into one

I have this code to read bytes to another file.
But I'm not able to concatenate two mp3 files into one.
Am I missing something?
public static void main(String[] args) {
String strFileName = ("D:/Music/Assb/Love.mp3");
BufferedOutputStream bos = null;
try
{
//create an object of FileOutputStream
FileOutputStream fos = new FileOutputStream(new File(strFileName));
//create an object of BufferedOutputStream
bos = new BufferedOutputStream(fos);
String str = "D:/Music/Assembled/Heart001.mp3"
+ "D:/Music/Assembled/Heart002.mp3";
/*
* To write byte array to file use,
* public void write(byte[] b) method of BufferedOutputStream
* class.
*/
System.out.println("Writing byte array to file");
bos.write(str.getBytes());
System.out.println("File written");
It`s suck. Mp3 file starts with headers. For correct merging you have to skip first 32 bytes. Try this.
try {
FileInputStream fistream1 = new FileInputStream(_file_name);
File f = new File(new File(_file_name).getParent()+"/final.mp3");
if(!f.exists())
{
f.createNewFile();
}
FileOutputStream sistream = new FileOutputStream((new File(_file_name)).getParent()+"/final.mp3");
int temp;
int size = 0;
temp = fistream1.read();
while( temp != -1)
{
sistream.write(temp);
temp = fistream1.read();
};
fistream1.close();
FileInputStream fistream2 = new FileInputStream(temp_file);
fistream2.read(new byte[32],0,32);
temp = fistream2.read();
while( temp != -1)
{
sistream.write(temp);
temp = fistream2.read();
};
fistream2.close();
sistream.close();
} catch (IOException e) {
e.printStackTrace();
}
You need to do this in two steps
String str = "D:/Music/Assembled/Heart001.mp3";
>>> ADD code to open the file given by str <<<<
bos.write(strFile.getBytes());
>>> Add code to close the file
str = "D:/Music/Assembled/Heart002.mp3";
>>> ADD code to open the file given by str <<<<
bos.write(strFile.getBytes());
>>> Add code to close the file
And as you can see you need code to open the mp3 file to read it
What Are You Trying For...Actually..if You Want To Read 2 Files to Byte Stream the dont String str = "D:/Music/Assembled/Heart001.mp3"
+ "D:/Music/Assembled/Heart002.mp3";
make str1=D:/Music/Assembled/Heart001.mp3 and str2=D:/Music/Assembled/Heart002.mp3 and read str1,str2 seperately through bufferedoutputsream
This code will work well and merge audio of similar type with in seconds...
try {
InputStream in = new FileInputStream("C:\\a.mp3");//firstmp3
byte[] buffer = new byte[1 << 20]; // loads 1 MB of the file
OutputStream os = new FileOutputStream(new File("C:\\output.mp3", true);//output mp3
int count;
while ((count = in.read(buffer)) != -1) {
os.write(buffer, 0, count);
os.flush();
}
in.close();
in = new FileInputStream("C:\\b.mp3");//second mp3
while ((count = in.read(buffer)) != -1) {
os.write(buffer, 0, count);
os.flush();
}
in.close();
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Categories

Resources