I am trying to read pdf using iText. Below is the code snippet for which i am getting exception as "not found as a file or resource":
public void readFromPdf(){
String content ="";
PdfReader reader = null;
try {
//String fileName is the string with the path to your .pdf file, for example resources/pdfs/preface.pdf
reader = new PdfReader("C:\\test\\demo.pdf");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int numberOfPages = reader.getNumberOfPages();
numberOfPages = numberOfPages + 1;
for (int page = 1; page < numberOfPages; page++){
try {
String content1Page = PdfTextExtractor.getTextFromPage(reader, page);
content = content + content1Page;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Could anyone please figure out whats going wrong?
I had the same problem - nobody gave me a really good answer & also my prof didn't find a bug.. Soo.. Now I'm using PDFBox from Apache http://pdfbox.apache.org It's quite simple to read pdfs.
put your demo.pdf inside assets in your project folder and use this:
reader = new PdfReader(openAssets().open("demo.pdf"));
as long as that contstructor can accept an input stream it should work.
Related
I am trying to upload Images/Videos which are taken through Device camera to server at a specific folder which can be retrieved later in a dashboard.
I have gone through numerous posts and tutorials and all of them are basically using a JSP to choose a file and then upload it or they are using PHP as a server side code to upload it.
I have my whole backend developed in JAVA SERVLET and I need to include this upload/download functionality.
Basically what I want is to make a POST request using Retrofit or Volley to make a server request and file should be uploaded. (It's like when we use POSTMAN to fire an api call and choose an image as binary file to upload).
Links which I have tried :
Link 1 , Link 2, Link 3 and a lot more. All of them include JSP or something to choose file, I need to pass the media(image/video) as a parameter to the POST request.
So I finally managed to achieve it. I had to post an image/video as well as a JSON corresponding to that media.
My solution is as follows :
#WebServlet("/ImageUploadServlet")
#MultipartConfig
public class ImageUploadServlet extends HttpServlet {
..............
.............
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
long req_received_time=System.currentTimeMillis();
String to_be_saved_location="";
System.out.println("JSON received is : "+request.getParameter("input_json"));
JSONObject req = null;
try {
req = readPOST(request.getParameter("input_json"));
to_be_saved_location = "your_location";
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
SqlUtil.incident_reporting(xxx);// function to enter data in sql
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream in = request.getPart("image").getInputStream();//change it to video(it's just a parameter name)
OutputStream out = new FileOutputStream("/Users/driftking9987/Documents/Stuffs/"+to_be_saved_location+".jpg");//Add .mp4 for video
//OutputStream out = new FileOutputStream("/var/www/html/media/abc.mp4");
copy(in, out); //The function is below
out.flush();
out.close();
}
public static long copy(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[4096];
long count = 0L;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
While saving it on the server, I gave the tomcat user the permission to write in the media folder.
Below is the POSTMAN screenshot.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm trying to get text from server and then check it a to know what actions to take with the text adopted. The problem is that when I try to check if the received text for example is "Exited" the query always return the value "false" when the received text is really "Exited".
Here is the code :
class Get_Message_From_Server implements Runnable
{
public void run()
{
InputStream iStream = null;
try
{
iStream = Duplex_Socket_Acceptor.getInputStream();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//Create byte array of size image
byte[] Reading_Buffer = null;
try
{
Reading_Buffer = new byte [Duplex_Socket_Acceptor.getReceiveBufferSize()];
//New_Buffer = new byte [100];
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] Byte_Char_1 = new byte[1];
int Byte_String_Lenght = 0;
//read size
try
{
iStream.read(Reading_Buffer);
String Reading_Buffer_Stream_Lenghtor = new String(Reading_Buffer);
//System.out.println("full : " + Reading_Buffer_Stream_Lenghtor);
Byte_String_Lenght = Reading_Buffer_Stream_Lenghtor.indexOf(new String(Byte_Char_1));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//Convert to String
Meassage = new String(Reading_Buffer);
Meassage = Meassage.substring(0, Byte_String_Lenght);//The text that received
Message_Getted = 1;
}
}
The query :
if(Message_1 != "Exited")//the message query
{
System.out.println("Continued 253");
continue;
}
Its always return the value - false
its important to know that the message is in Utf - 8 encoding
so how i can to fix the issue ?
If you compare strings by using oparators, Java will not look at the contents of the string but at the reference in memory. To compare String content in Java, you should use the following:
String Message_1; // Hopefully has a value sent by the server
if(Message_1.equals("Exited")) {
// Do stuff when exited
} else {
// Do stuff when not exited
}
String is a variable - and variables should start with lower Case letter - Please read Java Code conventions. Also to check if your message contains string you thing it should just do System.out.println(Message_1); and if the message contains what you expect you compare string doing
if(Message_1.equals("Exited")) {
System.out.println("Yes they are equal");
} else {
System.out.println("No they are not");
}
If this will print "No they are not" that simply means that your variable Message_1 is not what you think it is.. As simple as that. There is no such a thing as .equals method does not work. Its your variable that doesn't ;)
Hello,
I am trying to read a file with a Scanner so I can use the input of the strings to construct other objects. However my scanner is always throwing a NullPointerException when trying to create it. I have a pig.txt text file in the res/raw folder but my scanner can not seem to access it. I do not know what I am doing wrong. I have comment out other code of the method but still get an exception.
public void loadAchievements() {
try {
Scanner s = new Scanner(getResources().openRawResource(R.raw.pig));
/**
* s = s.useDelimiter("."); Scanner StringScanner; StringScanner =
* new Scanner(s.next()); StringScanner =
* StringScanner.useDelimiter(":"); String keep =
* StringScanner.next(); String StringKeeper = StringScanner.next();
* this.achievementBoard.add(new Achievement_Item(keep,
* StringKeeper)); StringScanner.close(); s.close();
**/
} catch (NullPointerException e) {
e.printStackTrace();
System.out.println("NULLPOINTER");
}
}
I had this problem today, and I resolved somehow.
I know that old question, but I would share it if others have stuck.
public class Question {
private int numberOfQuestion;
private String[] myquestion;
public Question(InputStream file_name) {
Scanner scanner = null;
try {
scanner = new Scanner(file_name);
} catch (Exception e) {
Log.d("Question", "Scanner :" + e);
System.exit(1);
}
this.numberOfQuestion = scanner.nextInt();
scanner.nextLine();
myquestion = new String[numberOfQuestion];
for (int i = 0; i < numberOfQuestion; ++i) {
myquestion[i] = scanner.nextLine();
}
scanner.close();
}
---------------------------------------------------------
call:
try {
MyScanner myScanner = new MyScanner(getResources().openRawResource( R.raw.input_question));
} catch (Exception e) {
Log.d("Error", "input_question.txt");
}
openRawResource() method can only be used to open drawable, sound, and raw resources; it will fail on string and color resources. Since your pig.txt is a text file that contains a String, openRawResource() won't be able to open a new stream therefore your stream is null.
I'm trying to write a json file using android like this:
String jsonString = broadcastDataArray.toString();
Writer output = null;
File fileAnnouncement = new File("announcement.json");
try {
output = new BufferedWriter(new FileWriter(fileAnnouncement));
output.write(jsonString);
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and now i'm trying to load/read the file using phonegap. Using this method shown here, i am able to read a file that was included in my application source. But i want to read some file that was generated by the android code.
Is there anyway to do this? Is there any specific directory where the file could be accessed from Java android and Phonegap/Sencha ?
Any kind of help or pointer is appreciated. Thanks.
You can do this in following way.
Write this function in your Android activity to write data in text file.
public void WriteDataToFile(String sFileName, String sBody){
try
{
FileWriter f = new FileWriter("/sdcard/data.txt");
f.append(sBody);
f.flush();
f.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
And, now you can read that file from your Sencha/Phonegap app by calling this function.
var user_data = function(){
var request = new XMLHttpRequest();
request.open("GET", "/sdcard/data.txt");
request.onreadystatechange = function() {
if (request.readyState == 4) {
// alert("*" + request.responseText + "*");
data = request.responseText;
}
}
request.send();
}
What is the best way to determine a file type in Android?
I want to check if the given file is an image, a music file, etc.
Include some mime.types files in your assets folder (for example from /etc/mime.types).
Include activation.jar (from JAF) in your build path.
Use something like this:
try {
MimetypesFileTypeMap mftm =
new MimetypesFileTypeMap(getAssets().open("mime.types"));
FileTypeMap.setDefaultFileTypeMap(mftm);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Then use FileDataSource.getContentType() to obtain file types.
public static String getMimeType(String fileUrl) {
String extension = MimeTypeMap.getFileExtensionFromUrl(fileUrl);
final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
return (mimeType != null) ? mimeType : "unknown";
}
A common way is by their extension only, or you can parse the header, but it should be too much slower and more complex for your apps.