This question already has answers here:
How to extract file extension from byte array
(3 answers)
Closed 7 years ago.
I am developing a web app, which has the functionality of displaying images obtained from a server. I learned that I can do it by returning byte array in response.
It seems that I am able to do it through:
#RequestMapping(value = "url/img", method = RequestMethod.POST)
#ResponseBody
public MyDto proceedDocumentFromUrl(#RequestParam final String url) throws IOException {
return somethingDoer.do(toByteArray(new URL(url).openStream());
}
somethingDoer.do returns Dto object which contains byte[] In field named image. For test purposes I would like to determine the image extension (it is always .jpg).
How can I do that? I was looking in Wiki and W3 documents for some clue(I suppose it is about first few bytes) but was unable to find a solution.
Please check this getFormatName(file) method and check Class ImageReader
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
public class Main {
public static void main(String[] argv) throws Exception {
File file = new File("image.gif");
System.out.println(getFormatName(file));
InputStream is = new FileInputStream(file);
is.close();
System.out.println(getFormatName(is));
}
private static String getFormatName(Object o) {
try {
ImageInputStream iis = ImageIO.createImageInputStream(o);
Iterator iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
return null;
}
ImageReader reader = (ImageReader) iter.next();
iis.close();
return reader.getFormatName();
} catch (IOException e) {
}
return null;
}
}
Please check https://github.com/arimus/jmimemagic to get extension from byte[]
byte[] data = someData
MagicMatch match = Magic.getMagicMatch(data);
System.out.println( match.getMimeType());
Related
My java code is:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class celebGrepper {
static class CelebData {
URL link;
String name;
CelebData(URL link, String name) {
this.link=link;
this.name=name;
}
}
public static String grepper(String url) {
URL source;
String data = null;
try {
source = new URL(url);
HttpURLConnection connection = (HttpURLConnection) source.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
/**
* Attempting to fetch an entire line at a time instead of just a character each time!
*/
StringBuilder str = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while((data = br.readLine()) != null)
str.append(data);
data=str.toString();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
public static ArrayList<CelebData> parser(String html) throws MalformedURLException {
ArrayList<CelebData> list = new ArrayList<CelebData>();
Pattern p = Pattern.compile("<td class=\"image\".*<img src=\"(.*?)\"[\\s\\S]*<td class=\"name\"><a.*?>([\\w\\s]+)<\\/a>");
Matcher m = p.matcher(html);
while(m.find()) {
CelebData current = new CelebData(new URL(m.group(1)),m.group(2));
list.add(current);
}
return list;
}
public static void main(String... args) throws MalformedURLException {
String html = grepper("https://www.forbes.com/celebrities/list/");
System.out.println("RAW Input: "+html);
System.out.println("Start Grepping...");
ArrayList<CelebData> celebList = parser(html);
for(CelebData item: celebList) {
System.out.println("Name:\t\t "+item.name);
System.out.println("Image URL:\t "+item.link+"\n");
}
System.out.println("Grepping Done!");
}
}
It's supposed to fetch the entire HTML content of https://www.forbes.com/celebrities/list/. However, when I compare the actual result below to the original page, I find the entire table that I need is missing! Is it because the page isn't completely loaded when I start getting the bytes from the page via the input stream? Please help me understand.
The Output of the page:
https://jsfiddle.net/e0771aLz/
What can I do to just extract the Image link and the names of the celebs?
I know it's an extremely bad practice to try to parse HTML using regex and is the stuff of nightmares, but on a certain video training course for android, that's exactly what the guy did, and I just wanna follow along since it's just in this one lesson.
This question already has answers here:
How do you Programmatically Download a Webpage in Java
(11 answers)
Closed 6 years ago.
How can I make the below code, save the webpage it self to txt file, I don't need the code of the webpage I need the webpage itself to be saved as text, like when we press CTRL + S and choose save as txt.
As well, how to make the browse hidden.
Thank you in advance :)
import java.awt.Desktop;
import java.io.File;
import java.net.URI;
public class Main {
public static void main(String[] args) throws Exception {
Desktop d = Desktop.getDesktop();
String url = "http://w3-01.ibm.com/pc/entitle/pg2/Service.wss/mts/Lookup?type=8205&serial=06202ET";
d.browse(new URI(url));
}
}
Here is a working example in Java 8:
import java.io.*;
import java.net.URL;
public class Main {
public static void main(String[] args) throws IOException {
URL url = new URL("https://www.google.com/");
String file = System.getProperty("java.io.tmpdir") + "google.txt";
System.out.println("Saving file to " + file);
try (InputStream in = url.openStream();
OutputStream os = new FileOutputStream(file)) {
int b;
while ((b = in.read()) != -1) {
os.write(b);
}
}
}
}
This question already has an answer here:
Apache POI Parsing error
(1 answer)
Closed 7 years ago.
I am getting the below Exception when I am trying to read an Excel file:
Exception in thread "main" java.lang.IllegalAccessError: tried to access method org.apache.poi.util.POILogger.log(ILjava/lang/Object;)V from class org.apache.poi.openxml4j.opc.PackageRelationshipCollection
at org.apache.poi.openxml4j.opc.PackageRelationshipCollection.parseRelationshipsPart(PackageRelationshipCollection.java:304)
at org.apache.poi.openxml4j.opc.PackageRelationshipCollection.<init>(PackageRelationshipCollection.java:156)
at org.apache.poi.openxml4j.opc.PackageRelationshipCollection.<init>(PackageRelationshipCollection.java:124)
at org.apache.poi.openxml4j.opc.PackagePart.loadRelationships(PackagePart.java:559)
at org.apache.poi.openxml4j.opc.PackagePart.<init>(PackagePart.java:112)
at org.apache.poi.openxml4j.opc.PackagePart.<init>(PackagePart.java:83)
at org.apache.poi.openxml4j.opc.PackagePart.<init>(PackagePart.java:128)
at org.apache.poi.openxml4j.opc.ZipPackagePart.<init>(ZipPackagePart.java:78)
at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:218)
at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:662)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:223)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:186)
at readAndWriteToExcel.ReadingExcel.main(ReadingExcel.java:36)
My code is:
package readAndWriteToExcel;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
public class ReadingExcel {
private static final Log LOG = LogFactory
.getLog(ReadingExcel.class);
public static void main(String[] args) throws Exception {
String SAMPLE_PERSON_DATA_FILE_PATH = "C:/Users/Documents/Test Data 5.xlsx";
File file = new File(SAMPLE_PERSON_DATA_FILE_PATH);
InputStream inputStream = new FileInputStream(file);
// The package open is instantaneous, as it should be.
OPCPackage pkg = null;
try {
ExcelWorkSheetRowCallbackHandler sheetRowCallbackHandler = new ExcelWorkSheetRowCallbackHandler(
new ExcelRowContentCallback() {
public void processRow(int rowNum, Map<String, String> map) {
// Do any custom row processing here, such as save
// to database
// Convert map values, as necessary, to dates or
// parse as currency, etc
System.out.println("rowNum=" + rowNum + ", map=" + map);
}
});
pkg = OPCPackage.open(inputStream);
ExcelSheetCallBack sheetCallback = new ExcelSheetCallBack() {
private int sheetNumber = 0;
public void startSheet(int sheetNum) {
this.sheetNumber = sheetNum;
System.out.println("Started processing sheet number=" + sheetNumber);
}
public void endSheet() {
System.out.println("Processing completed for sheet number=" + sheetNumber);
}
};
System.out.println("Constructor: pkg, sheetRowCallbackHandler, sheetCallback");
ExcelReader example1 = new ExcelReader(pkg,
sheetRowCallbackHandler, sheetCallback);
example1.process();
System.out.println("nConstructor: filePath, sheetRowCallbackHandler, sheetCallback");
ExcelReader example2 = new ExcelReader(SAMPLE_PERSON_DATA_FILE_PATH, sheetRowCallbackHandler, sheetCallback);
example2.process();
System.out.println("nConstructor: file, sheetRowCallbackHandler, sheetCallback");
ExcelReader example3 = new ExcelReader(file,
sheetRowCallbackHandler, null);
example3.process();
} catch (RuntimeException are) {
LOG.error(are.getMessage(), are.getCause());
} catch (InvalidFormatException ife) {
LOG.error(ife.getMessage(), ife.getCause());
} catch (IOException ioe) {
LOG.error(ioe.getMessage(), ioe.getCause());
} finally {
IOUtils.closeQuietly(inputStream);
try {
if (null != pkg) {
pkg.close();
}
} catch (IOException e) {
// just ignore IO exception
}
}
}
}
Is there a simple way to read and edit an Excel file (xls and xlsx) with more than 50k records? I have searched a lot and worked with a few available codes.
But I was not successful, I keep ending up with one Exception or another.
I was getting the same error:
"Handler processing failed; nested exception is
java.lang.IllegalAccessError: tried to access method
org.apache.poi.util.POILogger.log(ILjava/lang/Object;)V from class
org.apache.poi.openxml4j.opc.PackageRelationshipCollection"
After updating maven and trying to access PackageRelationshipCollection and POILogger classes in eclipse things worked fine for me. Make sure you have all the required jars i.e poi, poi-ooxml, poi-ooxml-schemas.
My code is
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import org.dcm4che2.imageio.plugins.dcm.DicomImageReadParam;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class DicomToJpeg {
public static void main(String args[]) throws IOException, Exception
{
dicomToJpeg("d:/F74AFBC7");
}
public static void dicomToJpeg(String args) throws IOException, Exception {
// TODO Auto-generated method stub
try
{
File myDicomFile = new File(args);
BufferedImage myJpegImage = null;
Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");
ImageReader reader = (ImageReader) iter.next();
DicomImageReadParam param = null;
try{
param = (DicomImageReadParam) reader.getDefaultReadParam();
}
catch (Exception e) {
e.printStackTrace();
}
ImageInputStream iis=ImageIO.createImageInputStream(myDicomFile);
reader.setInput(iis, false);
myJpegImage = reader.read(0, param);
iis.close();
if (myJpegImage == null) {
System.out.println("\nError: couldn't read dicom image!");
return;
}
File myJpegFile = new File("d:/demo.jpg");
OutputStream output = new BufferedOutputStream(new FileOutputStream(myJpegFile));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);
encoder.encode(myJpegImage);
System.out.println("Image Create successufully");
output.close();
}
catch(IOException e){
System.out.println("\nError: couldn't read dicom image!"+ e.getMessage());
return;
}
}
}
When i execute in java project using eclipse it work fine...
But when i execute using web application and in this i call it from controller page like
DicomToJpeg.dicomToJpeg("d:/F74AFBC7");
then it gives error like...
java.util.NoSuchElementException
at javax.imageio.spi.FilterIterator.next(Unknown Source)
at javax.imageio.ImageIO$ImageReaderIterator.next(Unknown Source)
at javax.imageio.ImageIO$ImageReaderIterator.next(Unknown Source)
at com.lifecare.controller.DicomToJpeg.dicomToJpeg(DicomToJpeg.java:32)
How to solve this error please help me....
The javadoc to ImageIO.getImageREadersByFormatName says:
Returns an Iterator containing all currently registered ImageReaders
that claim to be able to decode the named format.
If you access the iterator without checking if it has an element, you will get an exception.
Since it runs in you IDE and not on the server, you may have a look if the image readers for the DICOM is in the application's classpath on the server.
However, I would also like to know how do you call the above class. Is it from a servlet?
I solved it by calling ImageIO.scanForPlugins() before ImageIO.getImageReadersByFormatName()
ImageIO.scanForPlugins()
Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");
ImageReader reader = (ImageReader) iter.next();
This works perfectly on servlets
Try like this
BufferImage bi = ImageIO.read(dcm file name with path);
ImageIO.write(enter pathname with filename, format);
This question already has answers here:
How to get UTF-8 working in Java webapps?
(14 answers)
Closed 2 years ago.
Help fix the encoding in the servlet, it does not display Russian characters in the output.I will be very grateful for answers.
That is servlet code
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class servlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public static List<String> getFileNames(File directory, String extension) {
List<String> list = new ArrayList<String>();
File[] total = directory.listFiles();
for (File file : total) {
if (file.getName().endsWith(extension)) {
list.add(file.getName());
}
if (file.isDirectory()) {
List<String> tempList = getFileNames(file, extension);
list.addAll(tempList);
}
}
return list;
}
#SuppressWarnings("resource")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
request.setCharacterEncoding("utf8");
response.setContentType("text/html; charset=UTF-8");
String myName = request.getParameter("text");
List<String> files = getFileNames(new File("C:\\Users\\vany\\Desktop\\test"), "txt");
for (String string : files) {
if (myName.equals(string)) {
try {
File file = new File("C:\\Users\\vany\\Desktop\\test\\" + string);
FileReader reader = new FileReader(file);
int b;
PrintWriter writer = response.getWriter();
writer.print("<html>");
writer.print("<head>");
writer.print("<title>HelloWorld</title>");
writer.print("<body>");
writer.write("<div>");
while((b = reader.read()) != -1) {
writer.write((char) b);
}
writer.write("</div>");
writer.print("</body>");
writer.print("</html>");
}
catch (Exception ex) {
}
}
}
}
}
Here is what I have displayed instead of letters
п»ї ршншнщ олрршшш ошгншщ шгшг РѕСЂРѕСЂРіСЂРіСЂ Рто хрень работает СѓСЂР°
You're setting the character encoding on the request instead of the response. Change request.setCharacterEncoding("utf8"); to response.setCharacterEncoding("UTF-8");
Also: if the default character encoding of your system isn't UTF-8, you should explicitly set the encoding when reading from the file. To do that, you'd need to use an FileInputStream
pRes.setContentType("text/html; charset=UTF-8");
PrintWriter out = new PrintWriter(new OutputStreamWriter(pRes.getOutputStream(), "UTF8"), true);
use this one i got the exact result :)