I am trying to create ".zip" file from byte array but the error given appear everytime I am attempt to open it. Here is the code:
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.PrintWriter;
public class ReadTxtFile {
public static void BinFileContToBinArr(String path) throws Throwable{
BufferedReader inputStream = null;
PrintWriter outputStream = null;
try{
String el = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
inputStream = new BufferedReader(new FileReader(path));
FileOutputStream fos = new FileOutputStream("D:/texttNE22W.zip");
while((el=inputStream.readLine()) != null){
baos.write(el.getBytes());
}
byte[] b = baos.toByteArray();
for(int i = 0; i<b.length; i++){
System.out.print((char)b[i] + " ");
}
fos.write(b);
}
finally{
if (inputStream!=null){
inputStream.close();
}
if(outputStream!=null){
outputStream.close();
}
}
}
public static void main(String[] args) throws Throwable {
String path = "D:/text.txt";
BinFileContToBinArr(path);
}
}
I've made a research but didn't find a solution. Also, I tried to create a ".txt" file and it works. The only problem is when it comes to creating a ".zip".
Thank you beforehand ! By the way, if someone have encountered this problem before, feel free to vote up or leave me a comment if you wish, because I am interested if it is a common mistake.
You need to use ZipOutputStream instead of FileOutputStream.
Related
This a small part of my code. I want to read the file if it exists. If not, then create a new one. When I restart the program I want to work with the file that is saved. Eclipse says the error is on "ObjectInputStream inStream = new ObjectInputStream(file);" Not sure why.
rooms sbu = new rooms();
File saveFile = new File("SavedObj.obj");
if(saveFile.exists() == false)
{
System.out.println("No save file found. Creating a new file.");
try{
saveFile.createNewFile();
}catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
else {
FileInputStream file = new FileInputStream(saveFile);
ObjectInputStream inStream = new ObjectInputStream(file);
sbu= (room) inStream.readObject();
}
In the end of my code I store object like this:
FileOutputStream fileOut = new FileOutputStream(saveFile);
ObjectOutputStream outStream = new ObjectOutputStream(fileOut);
outStream.writeObject(sbu);
outStream.close();
isFinished= true;
Any help will be appreciated, thanks a lot!
You can't expect ObjectInputStream to convert text to objects automatically. readObject can only work for the file created by writeObject in ObjectOutputStream.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import com.pechen.Person;
public class Demo {
public static void main(String [] args) throws Exception{
String filename = "person.obj";
Person person = new Person();
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename));
out.writeObject(person);
out.close();
Person p;
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
p = (Person)in.readObject();
in.close();
System.out.println("Read Person: " + p.toString());
}
}
I use io scanner / System.out to copy text files. I tried using the same technique to copy pdf, video and image files. The result was that the files were copied, but they were corrupt (cannot open them). Also, the file size does not equal the original file size.
code
import java.awt.Desktop;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Scanner;
public class ScannerTest {
public static void main(String[] args) throws IOException {
PrintStream out =System.out;
long start = System.currentTimeMillis();
copyFile(new File("H:\\a.pdf"), new File("H:\\b.pdf"));// 2 file input, output
System.setOut(out);
System.out.println(System.currentTimeMillis()-start);
}
static String text=null;
public static void copyFile(File input,File output) throws IOException{
//Scanner read file
Scanner in= new Scanner(new FileInputStream(input));
StringBuilder builder =new StringBuilder();
try {
while(in.hasNextLine()){
text=in.nextLine();
builder.append(text);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
in.close();
}
//System.out
try {
OutputStream outputStream = new FileOutputStream(output);
PrintStream printStream = new PrintStream(outputStream);
System.setOut(printStream);
System.out.println(new String(builder));
Desktop.getDesktop().open(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
p/s: Not use IO other.(ex: BufferedInput/OutputStream)
There are two problems (at least):
you use nextLine() which will read up to the next "\r\n"', '\n', '\r', '\u2028', '\u2029' or '\u0085' and discard what ever it found as line separator (one or two characters). As you are not even using append(text).append('\n') I doubt that this will correctly copy multi-line text, let alone binary files where each of the possible line-terminators may have a different meaning.
you use Scanner and StringBuilder which are not safe for binary data. As the Documentation on new Scanner(java.io.InputStream) states:
Bytes from the stream are converted into characters using the underlying platform's default charset.
If any byte-sequence in you input file is not valid as e.g. UTF-8 (which is a common default charset) it is silently replaced by a generic 'could not read input'-character. For text-files this can mean, that a 'ä' is converted to '�', for binary files this can render the whole file unusable.
If you want to copy arbitrary (possibly binary) files I would recommend not taking any chances and stick to byte[] APIs. You could however also use a charset which is known to accept all byte-sequences unchanged like ISO-8859-1 when creating Scanner and PrintStream; you would than still need to refrain from using line-APIs that suppress the found line-separator.
This should do the trick:
import java.awt.Desktop;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
/**
* Created for http://stackoverflow.com/a/25351502/1266906
*/
public class CopyFile {
public static void main(String[] args) {
long start = System.currentTimeMillis();
copyFile(new File("H:\\a.pdf"), new File("H:\\b.pdf"));// 2 file input, output
System.out.println(System.currentTimeMillis() - start);
}
public static void copyFile(File input, File output) {
try {
try (FileInputStream inputStream = new FileInputStream(input);
OutputStream outputStream = new FileOutputStream(output)) {
byte[] buffer = new byte[4096];
do {
int readBytes = inputStream.read(buffer);
if (readBytes < 1) {
// end of file
break;
} else {
outputStream.write(buffer, 0, readBytes);
}
} while (true);
}
// Open result
Desktop.getDesktop().open(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
pre Java 7 you need to use try-finally:
public static void copyFile(File input, File output) {
try {
FileInputStream inputStream = new FileInputStream(input);
try {
OutputStream outputStream = new FileOutputStream(output);
try {
byte[] buffer = new byte[4096];
do {
int readBytes = inputStream.read(buffer);
if (readBytes < 1) {
// end of file
break;
} else {
outputStream.write(buffer, 0, readBytes);
}
} while (true);
} finally {
outputStream.close();
}
} finally {
inputStream.close();
}
// Open result
Desktop.getDesktop().open(output);
} catch (Exception e) {
e.printStackTrace();
}
}
I am reading a video file data in bytes and sending to another file but the received video file is not playing properly and is chattered.
Can anyone explain me why this is happening and a solution is appreciated.
My code is as follows
import java.io.*;
public class convert {
public static void main(String[] args) {
//create file object
File file = new File("B:/music/Billa.mp4");
try
{
//create FileInputStream object
FileInputStream fin = new FileInputStream(file);
byte fileContent[] = new byte[(int)file.length()];
fin.read(fileContent);
//create string from byte array
String strFileContent = new String(fileContent);
System.out.println("File content : ");
System.out.println(strFileContent);
File dest=new File("B://music//a.mp4");
BufferedWriter bw=new BufferedWriter(new FileWriter(dest));
bw.write(strFileContent+"\n");
bw.flush();
}
catch(FileNotFoundException e)
{
System.out.println("File not found" + e);
}
catch(IOException ioe)
{
System.out.println("Exception while reading the file " + ioe);
}
}
}
This question might be dead but someone might find this useful.
You can't handle video as string. This is the correct way to read and write (copy) any file using Java 7 or higher.
Please note that size of buffer is processor-dependent and usually should be a power of 2. See this answer for more details.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class FileCopy {
public static void main(String args[]) {
final int BUFFERSIZE = 4 * 1024;
String sourceFilePath = "D:\\MyFolder\\MyVideo.avi";
String outputFilePath = "D:\\OtherFolder\\MyVideo.avi";
try(
FileInputStream fin = new FileInputStream(new File(sourceFilePath));
FileOutputStream fout = new FileOutputStream(new File(outputFilePath));
){
byte[] buffer = new byte[BUFFERSIZE];
while(fin.available() != 0) {
bytesRead = fin.read(buffer);
fout.write(buffer, 0, bytesRead);
}
}
catch(Exception e) {
System.out.println("Something went wrong! Reason: " + e.getMessage());
}
}
}
Hope this also helpful for you - This can read and write a file into another file (You can use any file type to do that)
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Copy {
public static void main(String[] args) throws Exception {
FileInputStream input = new FileInputStream("input.mp4"); //input file
byte[] data = input.readAllBytes();
FileOutputStream output = new FileOutputStream("output.mp4"); //output file
output.write(data);
output.close();
}
}
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import javax.imageio.ImageIO;
public class Reader {
public Reader() throws Exception{
File file = new File("C:/Users/Digilog/Downloads/Test.mp4");
FileInputStream fin = new FileInputStream(file);
byte b[] = new byte[(int)file.length()];
fin.read(b);
File nf = new File("D:/K.mp4");
FileOutputStream fw = new FileOutputStream(nf);
fw.write(b);
fw.flush();
fw.close();
}
}
In addition to Jakub Orsula's answer, one needs to check the result of read operation to prevent garbage being written to end of file in last iteration.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class FileCopy {
public static void main(String args[]) {
final int BUFFERSIZE = 4 * 1024;
String sourceFilePath = "D:\\MyFolder\\MyVideo.avi";
String outputFilePath = "D:\\OtherFolder\\MyVideo.avi";
try(
FileInputStream fin = new FileInputStream(new File(sourceFilePath));
FileOutputStream fout = new FileOutputStream(new File(outputFilePath));
){
byte[] buffer = new byte[BUFFERSIZE];
int bytesRead;
while(fin.available() != 0) {
bytesRead = fin.read(buffer);
fout.write(buffer, 0, bytesRead);
}
}
catch(Exception e) {
System.out.println("Something went wrong! Reason: " + e.getMessage());
}
}
}
I create and write a file with a java method, then I want to read this file at runtime with another java method.But it throws java.io.FileNotFoundException error.
How could I fix this error?
Writer output=null;
File file = new File("train.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(trainVal[0] + "\n");
-------------------
and read code
FileInputStream fstreamItem = new FileInputStream("train.tx");
DataInputStream inItem = new DataInputStream(fstreamItem);
BufferedReader brItem = new BufferedReader(new InputStreamReader(inItem));
String phraseItem;
ArrayList<Double> qiF = new ArrayList<Double>();
while ((phrase = br.readLine()) != null) {
//doing somethinh here
}
Use the correct file name. This includes the path to the file. Also make sure that no one deleted the file between those two functions or renamed it.
The following is one of the best and convenient methods to read a file. Go through it instead of using traditional methods.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
final public class Main
{
public static void main(String... args)
{
File file = new File("G:/myFile.txt"); //Mention your absolute file path here.
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner=null;
try
{
scanner = new Scanner(file);
}
catch (FileNotFoundException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
String lineSeparator = System.getProperty("line.separator");
try
{
while(scanner.hasNextLine())
{
fileContents.append(scanner.nextLine()).append(lineSeparator);
}
}
finally
{
scanner.close();
}
System.out.println(fileContents); //Displays the file contents directly no need to loop through.
}
}
You have made a mistake in giving a proper file extension in your code.
FileInputStream fstreamItem = new FileInputStream("train.tx");
Should have been
FileInputStream fstreamItem = new FileInputStream("train.txt");
I wrote a code that writes compressed objects into a file, My questions is: is there a way that I could keep track of the increment of size of my file as the object being wrote in? here is my code:
public static void storeCompressedObjs(File outFile, ArrayList<Object[]> obj) {
FileOutputStream fos = null;
GZIPOutputStream gz = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream(outFile);
gz = new GZIPOutputStream(fos);
oos = new ObjectOutputStream(gz);
for (Object str : obj) {
oos.writeObject(str);
oos.flush();
//I was hoping to print outFile.length() here, but it doesn't work
}
} catch (IOException e) {
e.printStackTrace();
} finally {
oos.close();
gz.close();
fos.close();
}
}
I tried to use flush after every oos.writeObject(str); and then get the file size by using outFile.length(), but no matter how much I flush it, the file size remain unchanged until the last jump to its final size. Anyway that I could fix it? Thanks
The Apache Commons project provides a class CountingOutputStream, which you can put into your chain of OutputStreams. You can even have two of them:
package so5997784;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.io.output.CountingOutputStream;
public class CountBytes {
private static void dump(File outFile, Object... objs) throws IOException {
FileOutputStream fos = new FileOutputStream(outFile);
try {
CountingOutputStream compressedCounter = new CountingOutputStream(fos);
OutputStream gz = new GZIPOutputStream(compressedCounter);
CountingOutputStream uncompressedCounter = new CountingOutputStream(gz);
ObjectOutputStream oos = new ObjectOutputStream(uncompressedCounter);
for (Object obj : objs) {
oos.writeObject(obj);
oos.flush();
System.out.println(uncompressedCounter.getByteCount() + " -> " + compressedCounter.getByteCount());
}
oos.close();
System.out.println(uncompressedCounter.getByteCount() + " -> " + compressedCounter.getByteCount());
} finally {
fos.close();
}
}
public static void main(String[] args) throws IOException {
File outFile = new File("objects.out.gz");
dump(outFile, "a", "b", "cde", "hello", "world");
}
}