I want to copy the content of 2 file into third file - java

I have written code for one file content copy to another file. but i didn't able to copy second file content to third file .
for that i written following code :
try {
File infile = new File("d:\\vijay.txt");
File outfile = new File("d:\\ajay.txt");
FileInputStream instream = new FileInputStream(infile);
FileOutputStream outstream = new FileOutputStream(outfile);
byte[] buffer = new byte[1024];
int length;
while ((length = instream.read(buffer)) > 0) {
outstream.write(buffer, 0, length);
}
instream.close();
outstream.close();
System.out.println("File Copied successfully");
} catch (IOException ioe) {
ioe.printStackTrace();
}
Please help me ,Thanks in advance.

If you have Java 7, I would suggest you use the Files utils. For example:
Path source1 = Paths.get("src1.txt");
Path source2 = Paths.get("src2.txt");
Path destination = Paths.get("dest.txt");
out = Files.newOutputStream(destination, CREATE, APPEND);
Files.copy(source1, destination, StandardCopyOption.REPLACE_EXISTING);
Files.copy(source2, destination);

Do it as below:
try {
// the files to be copied
String[] filePaths = {"file1.txt", "file2.txt"};
// out file
File outfile = new File("d:\\ajay.txt");
FileOutputStream outstream = new FileOutputStream(outfile);
// loop to all files copied
for (String filePath : filePaths) {
FileInputStream instream = new FileInputStream(new File(filePath));
byte[] buffer = new byte[1024];
int length;
while ((length = instream.read(buffer)) > 0) {
outstream.write(buffer, 0, length);
}
// close each file on copy finished
instream.close();
}
// at the end close the output stream
outstream.close();
System.out.println("File Copied successfully");
} catch (IOException ioe) {
ioe.printStackTrace();
}
Now you can copy n files to one file.

You can try this:
try {
File infile = new File("/home/bobo/test/a.txt");
File infile1 = new File("/home/bobo/test/b.txt");
//The third file
File outfile = new File("/home/bobo/test/c.txt");
FileInputStream instream = new FileInputStream(infile);
FileInputStream instream1 = new FileInputStream(infile1);
FileOutputStream outstream = new FileOutputStream(outfile);
byte[] buffer = new byte[1024];
int length;
while ((length = instream.read(buffer)) > 0) {
outstream.write(buffer, 0, length);
}
while ((length = instream1.read(buffer)) > 0) {
outstream.write(buffer, 0, length);
}
instream.close();
instream1.close();
outstream.close();
System.out.println("File Copied successfully");
} catch (IOException ioe) {
ioe.printStackTrace();
}

just give it a try
public class Filescombining
{
public static void main(String[] args) throws IOException
{
ArrayList<String> list = new ArrayList<String>();
try
{
BufferedReader br = new BufferedReader(new FileReader( "input1.txt"));
BufferedReader r = new BufferedReader(new FileReader( "input2.txt"));
String s1 =null;
String s2 = null;
while ((s1 = br.readLine()) != null)
{
list.add(s1);
}
while((s2 = r.readLine()) != null)
{
list.add(s2);
}
}
catch (IOException e)
{
e.printStackTrace();
}
BufferedWriter writer=null;
writer = new BufferedWriter(new FileWriter("output.txt"));
String listWord;
for (int i = 0; i< list.size(); i++)
{
listWord = list.get(i);
writer.write(listWord);
writer.write("\n");
}
System.out.println("completed");
writer.close();
}
}
hope my help works happy coding

Related

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();

getResourceAsStream() is not working in built product

I am trying to copy the image files from resource folder to local system with using following code.
InputStream inStream = null;
OutputStream outStream = null;
File bfile = new File(directoryPath + "/icons/" + outputFileName);
inStream = MyClass.class.getClassLoader().getResourceAsStream("/images/" + imgFileName);
try {
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
if (inStream != null && outStream != null) {
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
}
System.out.println("File is copied successful!");
} catch (IOException e) {
e.printStackTrace();
}
This code works absolutely fine when I run through eclipse. But when i build the product, icons are not getting copied to local system.
I also tried
inStream = MyClass.class.getResourceAsStream("/images/" + imgFileName);
but no luck.
Any thoughts!
For opening an input stream consider using FileLocator API:
FileInputStream is = null;
FileOutputStream fo = null;
FileChannel inputChannel = null;
FileChannel outputChannel = null;
File bfile = new File(directoryPath + "/icons/" + outputFileName);
try {
is = FileLocator.openStream(Activator.getDefault().getBundle(), new Path("/images/" + imgFileName), false);
inputChannel = is.getChannel();
fo = new FileOutputStream(bfile);
outputChannel = fo.getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} finally {
// close everything in finally
}
Also, please note, that it is better to close streams and channels in the finally block

Socket file transfer failing

I have a server which uses the Sender class and a client which uses the Downloader class below. When the client connects to the server, it downloads the database.db and the default.docx perfectly, but when It starts to read the .png files, It throws this error:
java.io.IOException: Stream closed
at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:145)
at java.io.BufferedInputStream.read(BufferedInputStream.java:308)
at java.io.DataInputStream.readFully(DataInputStream.java:178)
at java.io.DataInputStream.readLong(DataInputStream.java:399)
at data.Downloader.<init>(Downloader.java:18)
at data.Connection.<init>(Connection.java:18)
at main(Client.java:17)
Here are my only two methods:
Downloader:
public Downloader(Socket socket) {
try {
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
DataInputStream dis = new DataInputStream(bis);
int filesCount = dis.readInt();
for (int i = 0; i < filesCount; i++) {
long size = dis.readLong();
String fileName = dis.readUTF();
System.out.println(fileName);
if (fileName.equals("database.db")) {
List<String> data = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(bis));
String line;
while ((line = reader.readLine()) != null) {
if (line.trim().length() > 0) {
data.add(line);
}
}
reader.close();
parse(data);
} else if (fileName.equals("default.docx")) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
for (int x = 0; x < size; x++) {
bos.write(bis.read());
}
bos.close();
document = bos.toByteArray();
} else if (fileName.contains(".png")) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
for (int x = 0; x < size; x++) {
bos.write(bis.read());
}
bos.close();
Signatures.signatures.add(bos.toByteArray());
}
}
dis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Sender:
public Sender(Socket socket) {
List<File> files = new ArrayList<File>();
files.add(new File(Directory.getDataPath("default.docx")));
files.add(new File(Directory.getDataPath("database.db")));
for (String signature : Directory.getSignaturePaths()) {
files.add(new File(signature));
}
try {
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);
dos.writeInt(files.size());
for (File file : files) {
System.out.println(file.getName() + file.length());
dos.writeLong(file.length());
dos.writeUTF(file.getName());
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
int theByte = 0;
while ((theByte = bis.read()) != -1) {
bos.write(theByte);
}
bis.close();
}
dos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Also, I checked the getSignaturePaths() method and It returns the correct paths and the .png files are there.
You closed the stream and then kept using the socket. Closing either the input stream or the output stream of a socket closes the other stream and the socket.

Zipping a csv file throws a "At Least One ZipEntry" using Java

What I am trying to do is to zip a generated csv file. The file does get generated without issue until it comes to this code here. So the code throws the exception at zos.close() here's the code
try {
FileOutputStream fos = new FileOutputStream(file.getPath());
ZipOutputStream zos = new ZipOutputStream(fos);
FileInputStream in = new FileInputStream(file.getPath());
String fullCSVFileName = file.getName();
String fullFileName = fullCSVFileName.substring(0, fullCSVFileName.length()-3);
String fullZipFileName = fullFileName + "zip";
ZipEntry ze= new ZipEntry(fullZipFileName);
if(ze != null) zos.putNextEntry(ze);
fos = new FileOutputStream("C:\\sourceLocation\\"+fullZipFileName);
zos = new ZipOutputStream(fos);
byte[] buffer = new byte[1024];
int len;// = in.read(buffer);
while ((len = in.read(buffer)) > 0) {
Logger.debug("in Loop, len = " + len);
zos.write(buffer, 0, len);
}
in.close();
zos.closeEntry();
zos.close();
Logger.debug("Zipping complete!");
} catch(IOException ex) {
Logger.error(ex);
}
Corrected Code
try{
String fullCSVFileName = file.getName();
String fullFileName = fullCSVFileName.substring(0, fullCSVFileName.length()-3);
String fullZipFileName = fullFileName + "zip";
FileOutputStream fos = new FileOutputStream("C:\\sourceLocation\\"+fullZipFileName);
ZipOutputStream zos = new ZipOutputStream(fos);
FileInputStream in = new FileInputStream(file.getPath());
ZipEntry ze= new ZipEntry(fullZipFileName);
if(ze != null){
zos.putNextEntry(ze);
}
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
zos.closeEntry();
zos.close();
Logger.debug("Zipping complete!");
}catch(IOException ex){
Logger.error(ex);
}
You create fos and zos once at the top of your code:
FileOutputStream fos = new FileOutputStream(file.getPath());
ZipOutputStream zos = new ZipOutputStream(fos);
then add a ZipEntry:
if(ze != null) zos.putNextEntry(ze);
then redifine them later:
fos = new FileOutputStream("C:\\sourceLocation\\"+fullZipFileName);
zos = new ZipOutputStream(fos);
then close the new zos. You never closed, nor wrote to the first zos (which had a ZipEntry) and never added a ZipEntry to the second (which you tried to close without any). Hence, the At Least One ZipEntry error.
------------ Edit --------------
Try adding zos.finish(), also, your close() methods should be in a finally block...
ZipOutputStream zos = null;
FileInputStream in = null;
try{
String fullCSVFileName = file.getName();
String fullFileName = fullCSVFileName.substring(0, fullCSVFileName.length()-3);
String fullZipFileName = fullFileName + "zip";
ZipOutputStream zos = new ZipOutputStream(
new FileOutputStream("C:\\sourceLocation\\"+fullZipFileName));
in = new FileInputStream(file.getPath());
zos.putNextEntry( new ZipEntry(fullZipFileName) );
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
zos.finish();
Logger.debug("Zipping complete!");
}catch(IOException ex){
Logger.error(ex);
}finally {
if ( zos != null ) {
try {
zos.close();
} catch ( Exception e ) {}
}
if ( in != null ) {
try {
in.close();
} catch ( Exception e ) {}
}
}

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