How to copy image in java using bufferedreader/writer - java

File file = new File("download.png");
File newfile = new File("D:\\Java.png");
BufferedReader br=null;
BufferedWriter bw=null;
try {
FileReader fr = new FileReader(file);
FileWriter fw = new FileWriter(newfile);
br = new BufferedReader(fr);
bw = new BufferedWriter(fw);
char[] buf = new char[1024];
int bytesRead;
while ((bytesRead = br.read(buf)) > 0) {
bw.write(buf, 0, bytesRead);
}
bw.flush();
}
catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Whats wrong with this code. Is it possible with BufferedReader and Writer Class??
I know how to to make copy of image using InputStream and OutputStream, So don't paste solution using that!!

Whats wrong with this code.
You're using text-based classes for binary data.
Is it possible with BufferedReader and Writer Class?
Not while you're dealing with binary data, no.
I know how to to make copy of image using InputStream and OutputStream, So don't paste solution using that!
That's the solution you should use, because those are the classes designed for binary data.
Fundamentally, using Reader or Writer for non-text data is broken, and asking for trouble. If you open up the file in a text editor and don't see text, it's not a text file... (Alternatively, it could be a text file that you're using the wrong encoding for, but things like images and sound aren't naturally text.)

Use javax.imageio.ImageIO utility class, which has lots of utility method related to images processing.
try{
File imagefile = new File("download.png");
BufferedImage image = ImageIO.read(imagefile);
ImageIO.write(image, "png",new File("D:\\Java.png"));
.....
}

Related

How to deal with read/write function for others file type in Java

I am doing a program which will receiving any file from my remote server, these files can be .doc, .pdf and some others file type. I will read the content in those files and write it into another new files with same file extension. But when i receive a .doc file from remote server and i try read the file and write into another file, it's show me something like this #²Ó\ç¨ Þ¢·S \Ò Þ¢·S \Ò PK £ JT in my test.doc. i have no idea on this issues, i try PrintStream,BufferedWriter or PrintWriter but unfortunately it's wouldn't help anything This is my source code for read/write the file
try
{
InputStream is1 = con1.getInputStream();
BufferedReader read1 = new BufferedReader (new InputStreamReader(is1));
String data1 = "" ;
while ((data1 = read1.readLine()) != null)
{
PrintWriter pw = new PrintWriter("test.doc","UTF-8");
pw.write(data1);
pw.close();
}
System.out.println("done");
}
catch(IOException e)
{
e.printStackTrace();
}
May i know what is the best way to do the read/write if we having difference file type ?
These file types have binary data and should not be read as characters. (Also, note that you are creating a new PrintWriter every time through the while loop. This will never work.) Just deal with the binary data directly. Something like this (untested) might work:
InputStream is1 = con1.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is1);
byte[] buffer = new byte[2048]; // or whatever size you want
int n;
OutputStream os = new FileOutputStream("test.doc");
while ((n = bis.read(buffer)) >= 0) {
os.write(buffer, 0, n);
}
os.close();
bis.close();
Also, you should be using a try with resources statement.
Other approach (more concise, more expressive):
Files.copy(is1, Paths.get("test.doc"), StandardCopyOption.REPLACE_EXISTING);

Can't write text into file

I want to write int into text file.
I wrote this code
public static void WriteInt(int i,String fileName){
File directory = new File("C:\\this\\");
if (!directory.exists()) {
directory.mkdirs();
}
File file = new File("C\\"+fileName);
FileOutputStream fOut = null;
try {
//Create the stream pointing at the file location
fOut = new FileOutputStream(new File(directory, fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(fOut);
try {
osw.write(i);
osw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
But in output file I have no int , just one symbol.
Any ideas to do it?
You should be using PrintWriter.print(int)
Writer.write() outputs one character, that's what it's for. Don't get confused by int parameter type. Wrap your osw in PrintWriter, don't forget to close that.
osw.write(i);
This line writes the character to the file whose unicode value is i
You should use PrintWriter to write your integer value.
OutputStreamWriter is a stream to print characters.
Try using a PrintWriter like this:
try(FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw)) {
pw.print(i);
}
I guess your problem is that you expected to literally find the number in human-readable format in your file, but the method of the OutputStreamWriter you're using (which receives a int) expect to receive a char representation. Have a look at the Ascii table for a reference of what int represents which char.
If you really wanted you write the number with characters, consider using a PrintWriter instead of a OutputStreamWriter. You could also change your int into a String (Integer.toString(i)) and still use your OutputStreamWriter

Write Velocity file forced in UTF-8

I'm using the following code to output a Velocity template to a file :
FileWriter fileWriterOut = new FileWriter(outFile);
logger.debug("encoding " + fileWriterOut.getEncoding());
fileWriterOut.write(template.getStringWriter().toString());
fileWriterOut.close();
Problem is :
Deployed in a non UTF-8 App Server, outFile is written using default encoding (iso-xxxx).
You can verify it with fileWriterOut.getEncoding()
It seems that no method in FileWriter class could set another encoding.
How can I force UTF-8 when writing my file ?
Use a FileOutputStream in combination with an OutputStreamWriter:
final OutputStream out = new FileOutputStream(...);
final Writer writer
= new OutputStreamWriter(out, Charset.forName("UTF-8"));
I've found a way to do this, I'm not sure that's the most convenient one, but it works correctly.
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
out.write(template.getStringWriter().toString());
}
catch ...
finally
{
try {
out.close();
} catch...
}

BufferedWriter not writing to .txt file even after flushing the writer

Here's the code I used, I get no errors or warnings but the file is empty, I created the aq.txt file and placed it in the workspace and it also shows in the project. I'm sure it's something stupid I'm missing but I just can't figure it out. Also, I tried all the other questions but the suggested answer is closing the stream and/or flushing it, both of which I do but they don't seem to work. Any help would be greatly appreciated!
Writer writer = null;
FileOutputStream fos= null;
try{
String xyz= "You should stop using xyz";
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(getFilesDir()+File.separator+"aq.txt")));
writer.write(xyz);
writer.flush();
}
catch(IOException e) {
System.out.println("Couldn't write to the file: " + e.toString());
}
finally{
if(writer != null){
try {
writer.close();
}
catch(IOException e1) {
e1.printStackTrace();
}
}
}
Try like this:
fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(fos));
writer.write(xyz);
writer.flush();
Context class provides a helper method Context.openFileOutput(String name, int mode) that will return a FileOutputStream to you for a file located in your applications Files directory.
I don't see any immediate reason why your way would not work, but I know I've used this other way successfully.
EDIT: After re-reading your question I think you are confused about where this file is going to be written to. It will not get written to the project folder inside of your workspace. This is going to be written to the internal storage of the android device that you run it on. Every application gets its own chunk of storage space located at \data\data\[package-name]\Files\ Your file is going to get written to there so you won't be able to immediately open it up and see the contents of it (unless your device is rooted.) You will instead have to open it up with java code and print its contents to the Log or some other output method in order to verify that your write did/did not work.
EDIT 2: Reading the file
FileInputStream in = openFileInput(FILE_NAME);
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader br = new BufferedReader(inputStreamReader);
String line = br.readLine();
Log.d("TAG", line);
This will read and output to the log the first line of the file.
This will certainly work :
File file = new File("fileName");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write("data to write in the file.");
writer.flush();

Android FileReader from R.raw.file

Really newbie question:
I have a .csv file that I need to read. I've put it in the raw folder. For convenience, Im' using the http://opencsv.sourceforge.net/ library for reading the file. The library provides this method for creating a CSVReader object:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
But I don0't get how to point this constructor to my file, since the file in Android is usually referenced like R.raw.file rather than a String address to the file.
Any help would be greatly appreciated.
You want to do something like this -
public void readCSVFromRawResource(Context context)
{
//this requires there to be a dictionary.csv file in the raw directory
//in this case you can swap in whatever you want
InputStream inputStream = getResources().openRawResource(R.raw.dictionary);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try
{
String word;//word
int primaryKey = 0;//primary key
Map dictionaryHash = new HashMap();
while ((word = reader.readLine()) != null)
{
if(word.length() < 7)
{
dictionaryHash.put(primaryKey,word );
primaryKey++;
if(primaryKey % 1000 == 0)
Log.v("Percent load completed ", " " + primaryKey);
}
}
//write the dictionary to a file
File file = new File(DICTIONARY_FILE_NAME);
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(DICTIONARY_FILE_NAME));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(dictionaryHash);
oos.flush();
oos.close();
Log.v("alldone","done");
}
catch (Exception ex) {
// handle exception
Log.v(ex.getMessage(), "message");
}
finally
{
try
{
inputStream.close();
}
catch (IOException e) {
// handle exception
Log.v(e.getMessage(), "message");
}
}
}
You can use this solution to get a String from the raw resource:
Android read text raw resource file
then use StringReader instead of FileReader with the CSVReader constructor.

Categories

Resources