Directly convert BufferedImage in a File object [duplicate] - java

This question already has answers here:
How to save a BufferedImage as a File
(6 answers)
Closed 8 years ago.
I saw many examples on the internet on how to convert a File into a BufferedImage, but I need to make a counter conversion.
I've tried some ways, but all are quite complicated.
I wonder if there is a direct way to accomplish this.
I have this in my code:
for (FileItem item : formItems) {
// processes only fields that are not form fields
if (!item.isFormField()) {
Date date = new Date();
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + date.getTime() + fileName + ".tmp";
File storeFile = new File(filePath);
BufferedImage tempImg = ImageIO.read(storeFile);
//I make process in the tempImg
//I need save it
item.write(tempImg);
}
}
I don't need write a FileItem, but the BufferedImage that I have processed.

File outputfile = new File("image.jpg");
ImageIO.write(bufferedImage, "jpg", outputfile);
Is this what you are looking for?

Related

How do you separate a HashMap onto separate lines using FileOutputStream? [duplicate]

This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 6 years ago.
I have a HashMap that I would like to write as separate lines to a text file. How do you go about doing this? In the SysOut above the code for writing to a text file I am printing out the values in the way that I would like to print them.
map.forEach((k,v)-> System.out.println(k+", "+v));
File file = new File(Constants.FILEPATH);
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(map);
s.close();
Don't use an ObjectOutputStream, use a PrintWriter:
try (PrintWriter out = new PrintWriter(file)) {
map.forEach((k,v) -> out.println(k+", "+v));
}

copy Chinese file source to destination in java [duplicate]

This question already has answers here:
Write chinese characters from one file to another
(2 answers)
Closed 7 years ago.
copying Chinese file in java using this code . but the destination file contains question mark (?) instead of Chinese character . is there any way in java to achieve this functionality..
File source = new File("H:\\work-temp\\file");
File dest = new File("H:\\work-temp\\file2");
try {
FileUtils.copyDirectory(source, dest);
} catch (IOException e) {
e.printStackTrace();
}
First of all, while copying a file, the destination should be a folder not file... so please change File dest = new File("H:\\work-temp\\file2"); to File dest = new File("H:\\work-temp");
Next you should use FileUtils.copyFile(source, dest); instead FileUtils.copyDirectory(source, dest);
Use one of the JDK 7 Files.copy methods. They create a binary copy of your file.
You are miss the extension of files for ex: file.txt and file2.txt:
File source = new File("H:\\work-temp\\file.txt");
File dest = new File("H:\\work-temp\\file2.txt");
For coping use this:
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try{
inputChannel = new FileInputStream(source).getChannel();
outputChannel = new FileOutputStream(dest).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} finally {
inputChannel.close();
outputChannel.close();
}
For more info go to this link

java - how to get file type in servlet 3.0 [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 7 years ago.
I have written a servlet using servlet3.0 for uploading the file and it uploads the file very well. But I want to save the file in the server in the format it is uploaded by the client.
Part filePart = request.getPart("chosenFile");
String filename = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();
System.out.println(filePart.getContentType().split("/")[1]);
InputStream inputStream =null;
OutputStream outputStream =null;
File fileSaveDirectory = new File(UPLOAD_DIR);
if(!fileSaveDirectory.exists()){
fileSaveDirectory.mkdir();
}
String content_path = UPLOAD_DIR+File.separator+filename;//earlier
//here I was appending the string ".pdf" to every file
//but now I want the file type to be the uploaded file type.
//say if user uploads in .jpeg or any other.
System.out.println("Content Path : "+content_path);
outputStream = new FileOutputStream(new File(content_path));
inputStream = filePart.getInputStream();
int read=0;
while((read=inputStream.read())!=-1){
outputStream.write(read);
}
if(outputStream!=null)
outputStream.close();
if(inputStream !=null)
inputStream.close();
How to keep the file type , the type of uploaded file. Please help !!!
See # http://docs.oracle.com/javaee/6/tutorial/doc/glraq.html:
private String getFileName(final Part part) {
final String partHeader = part.getHeader("content-disposition");
LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
So, when your (file upload) request is setup well/normal, the (http) header content-disposition will contain (among others, separated by ;) a filename attribute, which you can use (in the whole or) to extract the file suffix.

How to read content of file stored on server using java? [duplicate]

This question already has answers here:
How can I download and save a file from the Internet using Java?
(23 answers)
Closed 8 years ago.
How to read file stored on server using java?
I have .txt file stored on server, how to read contents of it.
String test, newq;
newq = "http://www.example.com/pqr.txt";
test = new String(Files.readAllBytes(Paths.get(newq)));
// variable test should contain pqr.txt content
What I am doing wrong?
That code works fine for files found in the file system. Path object is designed specifically for this.
When you want to access a remote file, it no longer works.
One easy way to read the file is this:
URL url = new URL("https://wordpress.org/plugins/about/readme.txt");
String text = new Scanner( url.openStream() ).useDelimiter("\\A").next();
It is not very pretty but it is small, it works and does not require any library.
With Apache Commons you can do it like this:
URL url = new URL("https://wordpress.org/plugins/about/readme.txt");
String text = IOUtils.toString(url.openStream());
Go through an HttpURLConnection and use a StringBuilder. Sketch code:
final URL url = new URL("http://www.example.com/pqr.txt");
final StringBuilder sb = new StringBuilder();
final char[] buf = new char[4096];
final CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT);
try (
final InputStream in = url.openStream();
final InputStreamReader reader = new InputStreamReader(in, decoder);
) {
int nrChars;
while ((nrChars = reader.read(buf)) != -1)
sb.append(buf, 0, nrChars);
}
final String test = sb.toString();

Converting Byte Array to Wav file [duplicate]

This question already has answers here:
Convert audio stream to WAV byte array in Java without temp file
(5 answers)
Closed 9 years ago.
After extensive research into the subject I have reached a brick wall.
All I want to do is add a collection of .wav files into a byte array, one after another, and output them all into one complete newly created .wav file. I extract all the .wav data into a byte array, skipping the .wav header and going straight for the data, then when it comes to writing it to the newly created .wav file I get an error like:
Error1: javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input stream
Error2: could not get audio input stream from input stream
The code is:
try
{
String path = "*********";
String path2 = path + "newFile.wav";
File filePath = new File(path);
File NewfilePath = new File(path2);
String [] folderContent = filePath.list();
int FileSize = 0;
for(int i = 0; i < folderContent.length; i++)
{
RandomAccessFile raf = new RandomAccessFile(path + folderContent[i], "r");
FileSize = FileSize + (int)raf.length();
}
byte[] FileBytes = new byte[FileSize];
for(int i = 0; i < folderContent.length; i++)
{
RandomAccessFile raf = new RandomAccessFile(path + folderContent[i], "r");
raf.skipBytes(44);
raf.read(FileBytes);
raf.close();
}
boolean success = NewfilePath.createNewFile();
InputStream byteArray = new ByteArrayInputStream(FileBytes);
AudioInputStream ais = AudioSystem.getAudioInputStream(byteArray);
AudioSystem.write(ais, Type.WAVE, NewfilePath);
}
Your byte array doesn't contain any header information which probably means that AutoSystem.write doesn't think it is really WAV data.
Can you create suitable header for your combined data?
Update: This question might hold the answer for you.

Categories

Resources