Java : Writing a String to a JPG File - java

Alright, so I am writing a small program that should have taken 10 minutes to complete however I am running into unforeseen problems.
The program should take in some old files I had in a vault program on my old phone, they are basically Jpg files but with an added "obscured" text to the front of the file.
So below is my code logic
get a folder input for the files,
create an arraylist containing each actual file.
call ConvertFiles to convert the file to a string,
delete the first 8 characters using substring and save that temp file to another arraylist containing the strings.
decode that string as base64 and input that into a bytearrayinputstream and save that to a bufferedimage.
This is where the problem occurs. I have content all the way up to the ImageIO.read(bis), so when it tries to write to a new file it throws the image == null
from the ImageTypeSpecifier. I have tried multiple ways of decoding and encoding the string, but any help is wanted and if any more information is needed I will provide it!
public class ImageConvert {
private File folder;
private ArrayList<File> files;
private ArrayList<String> stringFiles = new ArrayList<>();
private ArrayList<BufferedImage> bfImages = new ArrayList<>();
boolean isRunning = true;
Scanner scanner = new Scanner(System.in);
String folderPath;
public static void main(String[] args) {
ImageConvert mc = new ImageConvert();
mc.mainCode();
}
public void mainCode(){
System.out.println("Please enter the folder path: ");
folderPath = scanner.nextLine();
folder = new File(folderPath);
//System.out.println("folderpath: " + folder);
files = new ArrayList<File>(Arrays.asList(folder.listFiles()));
convertFiles();
}
public void convertFiles(){
for(int i = 0; i < files.size(); i++){
try {
String temp = FileUtils.readFileToString(files.get(i));
//System.out.println("String " + i + " : " + temp);
stringFiles.add(temp.substring(8));
} catch (IOException ex) {
Logger.getLogger(ImageConvert.class.getName()).log(Level.SEVERE,
null, ex);
}
}
//System.out.println("Converted string 1: " + stringFiles.get(0));
for(int j = 0; j < stringFiles.size(); j++){
BufferedImage image = null;
byte[] imageByte;
try {
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(stringFiles.get(j));
System.out.println(imageByte.toString());
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();
bfImages.add(image);
} catch (IOException ex) {
Logger.getLogger(ImageConvert.class.getName()).log(Level.SEVERE,
null, ex);
}
}
System.out.println("Image 1: " + bfImages.get(0));
for(int k = 0; k < bfImages.size(); k++){
try {
ImageIO.write(bfImages.get(k), "jpg",
new File(folderPath + "/" + k + ".jpg"));
} catch (IOException ex) {
Logger.getLogger(ImageConvert.class.getName()).log(Level.SEVERE,
null, ex);
}
}
}
}
This is an example of my files:

The following example uses the file you included with your question. You don't need to do any decoding, just read the file into memory, store the 8 byte String and then write the remaining bytes to a jpg from an 8 byte offset.
Just adapt the method below to work with your: "folder input for files". You don't need an ArrayList containing each actual jpg file.
public void convertFiles() {
File imgFile;
byte[] bytes;
FileOutputStream fos;
String temp;
for (int i = 0; i < files.size(); i++) {
temp = "";
try {
// 'read' method can be found below
bytes = read(files.get(i));
// read the 8 byte string from the beginning of the file
for(int j = 0; j < 8; j++) {
temp += (char) bytes[j];
}
imgFile = new File("img.jpg");
// points to './img.jpg'
fos = new FileOutputStream(imgFile);
// write from offset 8 to end of 'bytes'
fos.write(bytes, 8, bytes.length - 8);
fos.close();
} catch (FileNotFoundException e) {
// Logger stuff
} catch (IOException ex) {
// Logger stuff
}
System.out.println("[temp]:> " + temp);
}
}
read(File file) method adapted from a community wiki answer to File to byte[] in Java
public byte[] read(File file) throws IOException {
ByteArrayOutputStream ous = null;
InputStream ios = null;
try {
byte[] buffer = new byte[4096];
ous = new ByteArrayOutputStream();
ios = new FileInputStream(file);
int read = 0;
while ((read = ios.read(buffer)) != -1) {
ous.write(buffer, 0, read);
}
} finally {
try {
if (ous != null)
ous.close();
} catch (IOException e) {
}
try {
if (ios != null)
ios.close();
} catch (IOException e) {
}
}
return ous.toByteArray();
}
Output:
[temp]:> obscured
Image File:

Related

I need the file to be 1529 bytes and it does not work

Do I miss something? I need it to be 1529 bytes just. It's for my project and I can't understand what is going on.
I have a byte array, and I want to write one of them at a time randomly in the specified file.
import java.io.*;
import java.util.Random;
public class Cover {
public static byte[] aPenman = {97, 98, 99, 100, 101, 102};
public static long mTabulable(String fileName) throws IOException {
String path = "C:\\Users\\KOSTAS\\IdeaProjects\\prog\\src\\"+fileName;
File file = new File(path);
BufferedOutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream(file));
} catch (FileNotFoundException e) {
System.err.println("Unable to open file " + fileName);
}
long sum = 0;
try {
int i = 0;
while (file.length() != 1529){
int rand = new Random().nextInt(aPenman.length);
out.write(aPenman[rand]);
if (i < 1347) {
sum += aPenman[rand];
}
i++;
}
out.close();
}catch (Exception e){
System.err.println("Unable to open file " + fileName);
}
return sum;
}
}
I think that you are missing an:
out.flush();
just under your :
out.write(aPenman[rand]);
in the while loop
This forces any buffered output bytes to be written out to the underlying output stream.

Speed up copying in java

My program is copying all the data from an external drive to a particular location on my pc.
Here is my program :-
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Copy
{
public static void main(String[] args)
{
String[] letters = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I"};
File[] drives = new File[letters.length];
int copy=0;int l;File files[]=null;boolean pluggedIn=false;
FileInputStream fis=null;
FileOutputStream fos=null;
boolean[] isDrive = new boolean[letters.length];
for (int i = 0; i < letters.length; ++i)
{
drives[i] = new File(letters[i] + ":/");
isDrive[i] = drives[i].canRead();
}
System.out.println("FindDrive: waiting for devices...");
while (true)
{
try
{
for (int i = 0; i < letters.length; ++i)
{
pluggedIn = drives[i].canRead();
if (pluggedIn != isDrive[i])
{
if (pluggedIn)
{
System.out.println("Drive " + letters[i] + " has been plugged in");
files = drives[i].getAbsoluteFile().listFiles();
File file;
int fread;
for (l = 0; l < files.length; l++)
{
if (files[l].isFile())
{
file = new File("G://copied//" + files[l].getName());
file.createNewFile();
fis = new FileInputStream(drives[i].getAbsolutePath() + files[l].getName());
fos = new FileOutputStream(file);
while (true)
{
fread = fis.read();
if (fread == -1)
{
break;
}
fos.write(fread);
}
}
else
{
func(files[l].getAbsoluteFile(), "G://copied");
}
if(l==files.length-1)
{
System.out.print("copy complete");
fos.close();
fis.close();
}
}
}
else
{
System.out.println("Drive " + letters[i] + " has been unplugged");
}
isDrive[i] = pluggedIn;
}
}
Thread.sleep(5000);
}
catch (FileNotFoundException e) { }
catch (IOException e) { }
catch (InterruptedException e) {}
}
}
public static void func(File dir, String path)
{
File file = new File(path + "//" + dir.getName());
file.mkdir();
File[] files = dir.listFiles();
FileInputStream fis;
FileOutputStream fos;
int fread;
File file1;
for (int i = 0; i < files.length; i++)
{
if (files[i].isFile())
{
file1 = new File(file.getAbsolutePath() + "//" + files[i].getName());
try
{
file1.createNewFile();
fis = new FileInputStream(files[i]);
fos = new FileOutputStream(file1);
while (true)
{
fread = fis.read();
if (fread == -1)
{
break;
}
fos.write(fread);
}
} catch (FileNotFoundException e) {} catch (IOException e) {}
}
else
{
func(files[i], file.getAbsolutePath());
}
}
}
}
Now it is taking too long to copy large files.
Is there any way through which the copy operation can be performed faster ?
Thanx in advance for any suggestion.
If you can use Java 7 or later: java.nio.file.Files#copy.
If you are stuck with older Java: java.nio.channels.FileChannel#transferTo
A basic example that obtains FileChannel instances from the file streams:
public void copy( FileInputStream fis, FileOutputStream fos ) throws IOException {
FileChannel fic = fis.getChannel();
FileChannel foc = fos.getChannel();
long position = 0;
long remaining = fic.size();
while ( remaining > 0 ) {
long transferred = fic.transferTo( position, remaining, foc );
position += transferred;
remaining -= transferred;
}
}
You have to use a buffer. The copy logic should be something like:
byte[] buffer = new byte[4096];
int n;
while ((n = input.read(buffer) != -1)
{
output.write(buffer, 0, n);
}
output.close();
input.close();
This way, you copy a chunk of 4096 bytes at once, instead of byte per byte.
file.createNewFile();
Remove that. It is redundant. new FileOutputStream() will do that anyway. You're just adding processing here, and disk processing at that.
fis = new FileInputStream(drives[i].getAbsolutePath() + files[l].getName());
fos = new FileOutputStream(file);
Now add:
int count;
byte[] buffer = new byte[8192]; // or much more if you can afford the space
while ((count = fis.read(buffer)) > 0)
{
fos.write(buffer, 0, count);
}
Back to your code:
while (true)
{
fread = fis.read();
if (fread == -1)
{
break;
}
fos.write(fread);
}
Remove all that. Reading a byte at a time is as inefficient as it gets.

Read file of objects and write it back to a new one a single character at a time

How to read an entire record from a txt file, get each field separately and convert each field into a separate character stream. Then write the character streams of individual characters (in a loop) to a plain ASCII output text file.
I have my class definition, I just cannot seem to write the output file properly which has to be one individual plain ascii text character at a time. I just need a little help. Here is what I have so far:
----- This is my first question guys. Sorry if it isn't formatted well :( I'm trying to covert a file of objects to a plain ASCII character text file which i called "yankees.txt" I read it in with the ObjectInputStream then I'm supposed to get each field separately and convert each field into a seperate character stream, and write the characters one character at a time from each field to my "yankees.txt"
public class yankeesfilemain {
public static void main(String[] args) throws EOFException {
ObjectInputStream is;
OutputStream os;
yankees y;
int i, j, k;
String name, pos;
int number;
File fout;
try {
is = new ObjectInputStream(new
FileInputStream("yankees.yanks"));
y = (yankees)is.readObject();
fout = new File("yankees.txt");
os = new FileOutputStream(fout);
while (y != null) {
name = y.getname();
pos = y.getpos();
number = y.getnum();
for (i = 0; i < .length(); i++) {}
for (j = 0; j < .length(); j++) {
pos = y.getpos();
}
for (k = 0; k < .length(); k++) {
number = y.getnum();
}
break;
}
os.close();
is.close();
} catch(EOFException eof) {
eof.printStackTrace();
System.exit(0);
} catch(NullPointerException npe) {
npe.printStackTrace();
System.exit(0);
} catch(NumberFormatException nfe) {
nfe.printStackTrace();
System.exit(0);
} catch(IOException e) {
e.printStackTrace();
System.exit(0);
}
}
}
Please refer to the following code
public static void main(String[] args) throws IOException {
InputStream in = new FileInputStream("C:\\11.txt");
OutputStream out = new FileOutputStream("C:\\12.txt", true);
try {
byte[] buffer = new byte[1024];
while (true) {
int byteRead = in.read(buffer);
if (byteRead == -1)
break;
out.write(buffer, 0, byteRead);
}
}
catch (MalformedURLException ex) {
System.err.println(args[0] + " is not a URL Java understands.");
} finally {
if (in != null)
in.close();
if (out != null) {
out.close();
}
}
}

JPG downloading Applet with JAVA

I'm trying to program an applet for users to download jpg files from an url by entering the list of links of jpg images. When I use the procedure in JCreator's compiler, it works well. However, when I put it into an applet, I could not handle. I'm giving the actionlistener part and the method of the program below. Do you have any idea why it is not working?
Action Listener:
class DownloadListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String line = links.getText();
String[] linkarray = line.split("\n");
//int numOfLinks = linkarray.length;
String directoryUser = directory.getText();
try{
downloadImg(linkarray, directoryUser);
}
catch(IOException ex){
deneme.setText(ex.toString() + "Could not find file");
}
}
}
Method:
public void downloadImg(String[] linkarray, String directoryUser) throws IOException
{
for(int i=0; i<linkarray.length; i++)
{
URL url = new URL(linkarray[i]);
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
int j = 1;
String address = directoryUser + "/" + "oda" + Integer.toString(j) + ".jpg";
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(address));
fos.write(response);
fos.close();
j++;
}
}

Creating Folders in a Zip Folder in Java [duplicate]

This question already has answers here:
directories in a zip file when using java.util.zip.ZipOutputStream
(6 answers)
Closed 9 years ago.
My task requires me to save a file directory into a zip folder. My only problem is I need to keep the sub-folders as folders from the main Directory. The file system will look something like
C\\Friends
C:\\Friends\\Person1\\Information.txt
C:\\Friends\\Person2\\Information.txt
C:\\Friends\\Person3\\Information.txt
.
.
.
Right now I am able to write just the txt files inside of my zip folder, but in my zip folder I need to keep that folder structure. I know the way my code is right now will tell me the file I'm trying to write is closed(No access). My Functions thus far:
private String userDirectroy = "" //This is set earlier in the program
public void exportFriends(String pathToFile)
{
String source = pathToFile + ".zip";
try
{
String sourceDir = userDirectory;
String zipFile = source;
try
{
FileOutputStream fout = new FileOutputStream(zipFile);
ZipOutputStream zout = new ZipOutputStream(fout);
File fileSource = new File(sourceDir);
addDirectory(zout, fileSource);
zout.close();
System.out.println("Zip file has been created!");
}
catch(Exception e)
{
}
}
catch(Exception e)
{
System.err.println("First Function: " + e);
}
}
private static void addDirectory(ZipOutputStream zout, File fileSource) {
File[] files = fileSource.listFiles();
System.out.println("Adding directory " + fileSource.getName());
for(int i=0; i < files.length; i++)
{
if(files[i].isDirectory())
{
try
{
byte[] buffer = new byte[1024];
FileInputStream fin = new FileInputStream(files[i]);
zout.putNextEntry(new ZipEntry(files[i].getName()));
int length;
while((length = fin.read(buffer)) > 0)
{
zout.write(buffer, 0, length);
}
}
catch(Exception e)
{
System.err.println(e);
}
addDirectory(zout, files[i]);
continue;
}
try
{
System.out.println("Adding file " + files[i].getName());
//create byte buffer
byte[] buffer = new byte[1024];
//create object of FileInputStream
FileInputStream fin = new FileInputStream(files[i]);
zout.putNextEntry(new ZipEntry(files[i].getName()));
int length;
while((length = fin.read(buffer)) > 0)
{
zout.write(buffer, 0, length);
}
zout.closeEntry();
//close the InputStream
fin.close();
}
catch(IOException ioe)
{
System.out.println("IOException :" + ioe);
}
}
}
Any help would be much appreciated. Thank You
For each folder, you need to add a empty ZipEntry of the path.
For each file, you need to supply both the path and file name. This will require you to know the part of the path to strip off, this would be everything after the start directory
Expanded concept
So, from your example, if the start directory is C:\Friends, then the entry for C:\Friends\Person1\Information.txt should look like Person1\Information.txt
public void exportFriends(String pathToFile) {
String source = pathToFile + ".zip";
try {
String sourceDir = "C:/Friends";
String zipFile = source;
try {
FileOutputStream fout = new FileOutputStream(zipFile);
ZipOutputStream zout = new ZipOutputStream(fout);
File fileSource = new File(sourceDir);
addDirectory(zout, sourceDir, fileSource);
zout.close();
System.out.println("Zip file has been created!");
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getRelativePath(String sourceDir, File file) {
// Trim off the start of source dir path...
String path = file.getPath().substring(sourceDir.length());
if (path.startsWith(File.pathSeparator)) {
path = path.substring(1);
}
return path;
}
private static void addDirectory(ZipOutputStream zout, String sourceDir, File fileSource) throws IOException {
if (fileSource.isDirectory()) {
// Add the directory to the zip entry...
String path = getRelativePath(sourceDir, fileSource);
if (path.trim().length() > 0) {
ZipEntry ze = new ZipEntry(getRelativePath(sourceDir, fileSource));
zout.putNextEntry(ze);
zout.closeEntry();
}
File[] files = fileSource.listFiles();
System.out.println("Adding directory " + fileSource.getName());
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
addDirectory(zout, sourceDir, files[i]);
} else {
System.out.println("Adding file " + files[i].getName());
//create byte buffer
byte[] buffer = new byte[1024];
//create object of FileInputStream
FileInputStream fin = new FileInputStream(files[i]);
zout.putNextEntry(new ZipEntry(getRelativePath(sourceDir, files[i])));
int length;
while ((length = fin.read(buffer)) > 0) {
zout.write(buffer, 0, length);
}
zout.closeEntry();
//close the InputStream
fin.close();
}
}
}
}

Categories

Resources