Displaying .png files in java - java

I can display the text contained a .txt or .rtf file in java using this,
import java.io.*;
class test
{
public static void main(String args[])throws Exception
{
File f=new File("C:\\Users\\shinj\\Documents\\LIVE\\BEGINNER.txt");
String path = f.getAbsolutePath();//Pass file's absolute path
BufferedReader reader = new BufferedReader(new FileReader(path));
String line =null;
for (int i =1;i<=14;i++)
{
line=reader.readLine();
System.out.println(line);
}
}
}
But the same doesn't happen for any .png files.
What I want to know is that is there any way to display the contents of a .png files in the terminal output screen of java.
For example, if there is a picture of a stickman in such a file, I want to display the stickman on the terminal window.

Most of terminals can display only text data but some terminals allow to display emoji characters and images. For example it is possible in iTerm for macOS.

Related

Running multiple PDF through an PDFBox program

Currently I am trying to use PDFBox in Eclipse to run multiple PDF files in a folder through a text reader that will extract certain terms and output them into a text file that I will then convert to an excel sheet. Currently I have the program and it works correctly for a single PDF file:
public static void main(String args[]) throws IOException {
//Loading an existing document
File file = new File("ADE_acetylfuranoside_120319_pfister.pdf");
PDDocument document = PDDocument.load(file);
//Instantiate PDFTextStripper class
PDFTextStripper pdfStripper = new PDFTextStripper();
//Retrieving text from PDF document
String text = pdfStripper.getText(document);
//..."Actual code that extracts text"...
PrintStream o = new PrintStream(new File("output.txt"));
PrintStream console = System.out;
System.setOut(o);
System.out.println(finalSheet);
my problem is that I want to run 500 PDFs in one folder through this program on eclipse rather than putting in the name of each one individually. I also want it to output like:
Name1, Number1, ID1
Name2, Number2, ID2
but I think the way it is written now it will just overwrite line number one if I run multiple PDFs though it.
Thanks for the help!
For the first part, you could just use the File class with a FileFilter:
// directoryName could be as simple a "."
File folder = new File(directoryName);
File[] listOfFiles = folder.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getName().toLowerCase().endsWith(".pdf");
}
});
This gives you an array of File objects of all the files in a particular folder/directory. Now you can loop through it with pretty much the code you have.
On the output side, you'll likely want to correlate the output with the input. I'm a bit confused by your code and I'm guessing you'd just like an output file for each input file. So, perhaps, something like:
// index is the value you used to loop through the `listOfFiles` array
try( FileWriter fileWriter = new FileWriter(listOfFiles[index].getName() + ".output.txt" ) ) {
fileWriter.write( // the String text you want in the file );
}
This creates a file named (as taken from your example) "ADE_acetylfuranoside_120319_pfister.pdf.output.txt". Obviously this could change. In this case a new file is created for each input file.

Accessing a file in a runnable JAR [duplicate]

This question already has answers here:
Java resource as File
(6 answers)
Closed 9 years ago.
What I am attempting to do is store a text file (that won't change) inside the JAR of the program so that it can be read. The purpose of the text file is that it will be read in by one of my classes and the contents of the text file will be added to an JEditorPane. The file will basically be a tutorial and when the user clicks on the option to read the tutorial, the file contents will be read and displayed in a new window that pops up.
I have the GUI portion of it down, but as far as storing the file in the JAR so it can be accessed, I am at a lost. I've read that using an InputStream will work, but after trying a few things I haven't gotten it to work yet.
I also store images in the JAR to be used as icons for the GUI windows. This is accomplished with:
private Image icon = new ImageIcon(getClass()
.getResource("resources/cricket.jpg")).getImage();
But, this doesn't work when trying to get a file:
private File file = new File(getClass.getResource("resources/howto.txt"));
Here is my Class as it is now:
public class HowToScreen extends JFrame{
/**
*
*/
private static final long serialVersionUID = -3760362453964229085L;
private JEditorPane howtoScreen = new JEditorPane("text/html", "");
private Image icon = new ImageIcon(getClass().getResource("resources/cricket.jpg")).getImage();
private BufferedReader txtReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/resources/howto.txt")));
public HowToScreen(){
setSize(400,300);
setLocation(500,200);
setTitle("Daily Text Tutorial");
setIconImage(icon);
howtoScreen.setEditable(false);
howtoScreen.setText(importFileStream());
add(howtoScreen);
setVisible(true);
}
public String importFile(){
String text = "";
File file = new File("howto.txt");
Scanner in = null;
try {
in = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while(in.hasNext()){
text += in.nextLine();
}
in.close();
return text;
}
public String importFileStream(){
String text = "";
Scanner in = new Scanner(txtReader);
while(in.hasNext()){
text += in.nextLine();
}
in.close();
return text;
}
}
Ignore the importFile method as that is being removed in favor of storing the tutorial file inside the JAR, making the program wholly self contained as I am limited to how much space the program can use.
EDIT:
After trying all of the suggestions below, I checked to see if my JAR is packaging the text file in it and it is not. When opening the JAR with 7zip, in my resources folder the picture I use for icons is there, but not the text file.
You cannot use File inside a JAR file. You need to use InputStream to read the text data.
BufferedReader txtReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/resources/mytextfile.txt")));
// ... Use the buffered reader to read the text file.
Try the next (with the full path package):
InputStream inputStream = ClassLoader.getSystemClassLoader().
getSystemResourceAsStream("com/company/resources/howto.txt");
InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader in = new BufferedReader(streamReader);
for (String line; (line = in.readLine()) != null;) {
// do something with the line
}
You code will not compile. Class.getResource() returns a URL, and File has no constructor with a URL as an argument.
You can just use .getResourceAsStream() instead, it returns an InputStream directly, you just have to read the contents of the file from that stream.
Note: both of these methods return null if the resource is not found: don't forget to check for that...
the contents of the text file will be added to an JEditorPane.
See DocumentVewer & especially JEditorPane.setPage(URL).
Since the help is an embedded-resource it will be necessary to gain an URL using getResource(String) as detailed in the info. page.
.. tried this: URL url = this.getClass().getResource("resources/howto.txt");
Change:
URL url = this.getClass().getResource("resources/howto.txt");
To:
URL url = this.getClass().getResource("/resources/howto.txt"); // note leading '/'

Monitor folder for mp3

I have a homework to do and I don't know how to get started. I have to read from an external text file the paths of some random folders. I must make the paths for this folders available even I change the computer.
Then I have to output in the console the number of mp3 files found in every each folder.
My big problem is that I don't know how to make those paths work for every computer on which I run the program and also I don't know how the filter the content.
LATER EDIT: I've managed to write some code. I can search now for the mp3, but... can someone help me with this: how can i add a new path to the txt file from keyboard and also how can i remove an entire line from it?
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
String ext = ".mp3";
BufferedReader br = new BufferedReader(new FileReader("Monitor.txt"));
for (String line; (line = br.readLine()) != null;) {
findFiles(line, ext);
}
br.close();
}
private static void findFiles(String dir, String ext) {
File file = new File(dir);
if (!file.exists())
System.out.println(dir + " No such folder folder");
File[] listFiles = file.listFiles(new FiltruTxt(ext));
if (listFiles.length == 0) {
System.out.println(dir + " no file with extension " + ext);
} else {
for (File f : listFiles)
System.out.println("Fisier: " + f.getAbsolutePath());
}
}
}
import java.io.File;
import java.io.FilenameFilter;
public class FiltruTxt implements FilenameFilter{
private String ext;
public FiltruTxt(String ext){
this.ext = ext.toLowerCase();
}
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(ext);
}
}
I think that with "available even I change the computer" mean that you need to read the path from the file and not hard code it on your program so if you run in other computer you only need to change the text file and not the program.
But as #André Stannek had said in his comment, you must add to your question what have you tried and what is the exact programming problem you are facing.
When you face a problem, try to divide it in individual and more small problems. For example:
How to read a line from the console?
How to write a new line to a file?
Then try to search for a solution (if you can't think in one). For example in stack overflow, google and of course in the official documentation.
The official documentation:
http://docs.oracle.com/javase/tutorial/essential/io/index.html
Some questions in stackoverflow:
Read multiple lines from console and store it in array list in Java?
Read string line from console
How do I add / delete a line from a text file?
How to add a new line of text to an existing file in Java?
Or this links from Internet:
http://www.msccomputerscience.com/2013/01/write-java-program-to-get-input-from.html
This is the portal of the Java tutorials that you will found very useful when you are learning: http://docs.oracle.com/javase/tutorial/index.html

java file reader weird output

I set up a FileReader, and opened a file to read, but it gives me a weird output, that I can't seem to fix:
import java.io.BufferedReader;
import java.io.FileReader;
public class FileReading {
public static void main(String [] args) throws Exception {
FileReader file = new FileReader("/Users/danielpersonius/Desktop/test.rtf");
BufferedReader reader = new BufferedReader(file);
String text = "";
String line = reader.readLine();
while (line != null){
// So here, we want to print until it reaches 'null'
text += line;
line = reader.readLine();
}
System.out.println(text);
}
}
This is my output:
{\rtf1\ansi\ansicpg1252\cocoartf1265\cocoasubrtf200{\fonttbl\f0\fswiss\fcharset0
Helvetica;}{\colortbl;\red255\green255\blue255;}\margl1440\margr1440\vieww10800\viewh8400\viewkind0\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural\f0\fs24
\cf0 TEST}
TEST is what the rtf file says, but how do I get rid of all the other stuff I obviously don't want?
I'm on an IMac with OS X Mavericks
The problem is that your are probably creating your file in TextEdit. TextEdit does not save files as a raw text file. Instead it saves it in a RTF (Rich Text File) format which embeds formating commands. You need to use a text editor that can create an ASCII text file.
For more information on RTF.
Just use the same editor you use to write your code to create your "test.*" file :)
On your test file go to format in the toolbar, then click convert to .txt file for conversion.
This change would get rid of the weird output

java FileInputStream cannot find file

I'm very new at coding java and I'm having a lot of difficulty.
I'm suppose to write a program using bufferedreader that reads from a file, that I have already created named "scores.txt".
So I have a method named processFile that is suppose to set up the BufferedReader and loop through the file, reading each score. Then, I need to convert the score to an integer, add them up, and display the calculated mean.
I have no idea how to add them up and calculate the mean, but I'm currently working on reading from the file.
It keeps saying that it can't fine the file, but I know for sure that I have a file in my documents named "scores.txt".
This is what I have so far...it's pretty bad. I'm just not so good at this :( Maybe there's is a different problem?
public static void main(String[] args) throws IOException,
FileNotFoundException {
String file = "scores.txt";
processFile("scores.txt");
//calls method processFile
}
public static void processFile (String file)
throws IOException, FileNotFoundException{
String line;
//lines is declared as a string
BufferedReader inputReader =
new BufferedReader (new InputStreamReader
(new FileInputStream(file)));
while (( line = inputReader.readLine()) != null){
System.out.println(line);
}
inputReader.close();
}
There are two main options available
Use absolute path to file (begins from drive letter in Windows or
slash in *.nix). It is very convenient for "just for test" tasks.
Sample
Windows - D:/someFolder/scores.txt,
*.nix - /someFolder/scores.txt
Put file to project root directory, in such case it will be visible
to class loader.
Place the scores.txt in the root of your project folder, or put the full path to the file in String file.
The program won't know to check your My Documents folder for scores.txt
If you are using IntelliJ, create an input.txt file in your package and right click the input.txt file and click copy path. You can now use that path as an input parameter.
Example:
in = new FileInputStream("C:\\Users\\mda21185\\IdeaProjects\\TutorialsPointJava\\src\\com\\tutorialspoint\\java\\input.txt");
Take the absolute path from the local system if you'r in eclipse then right-click on the file and click on properties you will get the path copy it and put as below this worked for me In maven project keep the properties file in src/main/resources `
private static Properties properties = new Properties();
public Properties simpleload() {
String filepath="C:/Users/shashi_kailash/OneDrive/L3/JAVA/TZA/NewAccount/AccountConnector/AccountConnector-DEfgvf/src/main/resources/sample.properties";
try(FileInputStream fis = new FileInputStream(filepath);) {
//lastModi = propFl.lastModified();
properties.load(fis);
} catch (Exception e) {
System.out.println("Error loading the properties file : sample.properties");
e.printStackTrace();
}
return properties;
}`

Categories

Resources