Reading from text file to load images from resource folder - java

I wanted to make a way so that I can load all the Images in my source folder without having to code each line for each image, but I keep getting an error and have tried different ways to do this and I still can't figure it out. Is it just impossible?
Here is how it works: I save all the images I am going to need on a text file (in this case startUp.txt), then I store the lines in the text file in a linked-list(String) then I use a loop to get the images and store those in a linked-list(Image) so that I don't need to write code for every single Image to load.
Here is my code:
package com.game.task;
import java.awt.Image;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.Scanner;
import javax.swing.ImageIcon;
public class imagesTest {
public LinkedList<Image> storeImages = new LinkedList<Image>();
private LinkedList<String> storeStrings = new LinkedList<String>();
public imagesTest() {
load();
readimage();
}
public void readimage() {
for(int index = 0; index < storeStrings.size(); index++){
Image temp = new ImageIcon(this.getClass().getClassLoader().getResource("/res/"+storeStrings.get(index))).getImage();
storeImages.add(temp);
}
}
private void load() {
File file = new File("Data/startUp.txt");
try {
Scanner read = new Scanner(file);
while (read.hasNextLine()) {
storeStrings.add(read.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] arsg) {
imagesTest t = new imagesTest();
}
}
Exception:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:217)
at com.game.task.imagesTest.readimage(imagesTest.java:24)
at com.game.task.imagesTest.load(imagesTest.java:41)
at com.game.task.imagesTest.<init>(imagesTest.java:17)
at com.game.task.imagesTest.main(imagesTest.java:45)

I found a way to loop through the resource folder and it was not that hard.
All i had to do use make a method and keep calling it in a loop here is the code
package com.game.task;
import java.awt.Image;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.Scanner;
import javax.swing.ImageIcon;
public class imagesTest {
public LinkedList<Image> storeImages = new LinkedList<Image>();
private LinkedList<String> storeStrings = new LinkedList<String>();
public imagesTest() {
load();
start();
}
public void readimage(String f) {
Image temp = new ImageIcon(this.getClass().getResource("/res/"+f)).getImage();//looks for it
storeImages.add(temp);//put it in a linked-List(Image)
}
public void start(){
for(int index = 0; index < storeStrings.size(); index++){
readimage(storeStrings.get(index));//calling the methode to look in resource folder
}
}
//reads the text file and puts the out put in a linked-list(String)
private void load() {
File file = new File("Data/startUp.txt");
try {
Scanner read = new Scanner(file);
while (read.hasNextLine()) {
storeStrings.add(read.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] arsg) {
imagesTest t = new imagesTest();
}
}

Related

Java file copy to non empty destination folder

I'm having real difficulties figuring out how this needs to be coded without using FileUtils import. I have found thousands of tutorials on how to move files to empty folders, that's easy. The difficulty is finding out how Java can move files to directories that already have files in the folder. As I understand it the REPLACE_EXISTING parameter means it will overwrite identical file names if detected in the destination directory, but the directory doesn't have a file with a matching name of the file I'm attempting to copy/move. What am I missing? How can I make this happen?
java.nio.file.DirectoryNotEmptyException occuring.
enter code here
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class Move {
static File source = new File("sourcefolderhere");
static File destination = new File("destfolderhere");
public static void move(File src, File dest) throws IOException {
Files.move(src.toPath().toAbsolutePath(), dest.toPath().toAbsolutePath(),
StandardCopyOption.REPLACE_EXISTING);
}
public static void main(String[] args) throws IOException {
try {
if(source.isDirectory() && destination.isDirectory()) {
File[] content = source.listFiles();
for(int i = 0; i < content.length; i++) {
System.out.println(content[i]);
move(source, destination);
}
}
else if (!destination.isDirectory()){
System.out.println("create folder here");
destination.mkdir();
File[] content = source.listFiles();
for(int i = 0; i < content.length; i++) {
move(source, destination);
}
}
}
catch(Exception ex) { System.out.println(ex);
}
finally {
}
}
}
I tried the code in IDE File.move method with parameter StandardCopyOption.REPLACE_EXISTING works only if you have file in the destination folder. otherwise use File.move the normal way. I have also modified your code a little just to avoid code duplication.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
public class Move {
static File source = new File("sourcefolderhere");
static File destination = new File("destfolderhere");
public static void move(File src, File dest) throws IOException {
System.out.println(src.getName());
if(isExist(src.getName()))
Files.move(src.toPath().toAbsolutePath(), Paths.get(destination.getAbsolutePath()+File.separator+src.getName()) , StandardCopyOption.REPLACE_EXISTING);
else
Files.move(src.toPath().toAbsolutePath(), Paths.get(destination.getAbsolutePath()+File.separator+src.getName()));
}
public static boolean isExist(String souceFileName){
//If you are not using java 8 code
/*String[] destFiles = destination.list();
for(String fileName : destFiles){
if(souceFileName.equals(fileName))
return true;
}
return false;*/
return Arrays.stream(destination.list())
.anyMatch(fileName -> fileName.equals(souceFileName));
}
public static void main(String[] args) throws IOException {
try {
if(!source.isDirectory())
throw new IllegalArgumentException("Source Folder doesn't Exist");
if(!destination.exists())
destination.mkdir();
if (source.isDirectory() && destination.isDirectory()) {
File[] content = source.listFiles();
for (int i = 0; i < content.length; i++) {
System.out.println(content[i]);
move(content[i], destination);
}
}
} catch (Exception ex) {
System.out.println(ex);
} finally {
}
}
}```

How to access many resource images in a folder in a jar in Java?

I have got this class for loading blue images, which works fine in Eclipse but not in the exported jar. How can I access all the blue images in the folder (directory) called "blue" without knowing the names of the images?
public class Blue
{
public static void read() throws Exception
{
File directoryBlueImages = new File(
Blue.class.getResource("blue").getFile());
String[] blueImages = directoryBlueImages.list();
List<BufferedImage> blueImagesList = new ArrayList<>();
for (String blueImage : java.util.Objects.requireNonNull(blueImages))
{
blueImagesList.add(ImageIO
.read(Blue.class.getResourceAsStream("blue/" + blueImage)));
}
ApplicationImages.setBlueImages(blueImagesList);
}
}
UPDATE
I have tried this, but it does not work either. I am getting a NullPointer exception. I tried "/blue" and "blue" and even ".blue".
import java.awt.image.BufferedImage;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import javax.imageio.ImageIO;
import vokabeltrainer.ApplicationImages;
public class Blue
{
public static void read() throws Exception
{
List<BufferedImage> blueImagesList = new ArrayList<>();
try (Stream<Path> pathStream = Files.walk(Paths.get(Blue.class
.getClassLoader().getResource("blue").toURI().toURL().getPath()))
.filter(Files::isRegularFile))
{
for (Path file : (Iterable<Path>) pathStream::iterator)
{
blueImagesList.add(ImageIO
.read(Blue.class.getResourceAsStream(file.toString())));
;
}
}
ApplicationImages.setBlueImages(blueImagesList);
}
}
I adapted an answer from How to list the files inside a JAR file?
First I distinguish wether I am running from jar or Eclipse:
try
{
Blue.readZip(); // when inside jar
}
catch (Exception e)
{
try
{
Blue.read(); // during development
}
catch (Exception e1)
{
System.out.println("Could not read blue.");
e1.printStackTrace();
}
}
Then class Blue looks like this:
public class Blue
{
private static List<BufferedImage> blueImagesList = new ArrayList<>();
public static void read() throws Exception
{
File directoryBlueImages = new File(
Blue.class.getResource("blue").getFile());
String[] blueImages = directoryBlueImages.list();
for (String blueImage : java.util.Objects.requireNonNull(blueImages))
{
blueImagesList.add(ImageIO
.read(Blue.class.getResourceAsStream("blue/" + blueImage)));
}
ApplicationImages.setBlueImages(blueImagesList);
}
public static void readZip() throws Exception
{
CodeSource src = Blue.class.getProtectionDomain().getCodeSource();
if (src != null)
{
URL jar = src.getLocation();
ZipFile zipFile = new ZipFile(jar.getFile());
ZipInputStream zip = new ZipInputStream(jar.openStream());
while (true)
{
ZipEntry ze = zip.getNextEntry();
if (ze == null)
break;
String name = ze.getName();
if (name.startsWith("vokabeltrainer/resources/blue/"))
{
blueImagesList.add(ImageIO.read(zipFile.getInputStream(ze)));
}
}
}
else
{
throw new IOException("can not find code source for blue images");
}
ApplicationImages.setBlueImages(blueImagesList);
}
}

Creating an Arrylist in a Arraylist in Java

This is my first post so sorry if I mess something up or if I am not clear enough. I have been looking through online forums for several hours and spend more trying to figure it out for myself.
I am reading information from a file and I need a loop that creates an ArrayList every time it goes through.
static ArrayList<String> fileToArrayList(String infoFromFile)
{
ArrayList<String> smallerArray = new ArrayList<String>();
//This ArrayList needs to be different every time so that I can add them
//all to the same ArrayList
if (infoFromFile != null)
{
String[] splitData = infoFromFile.split(":");
for (int i = 0; i < splitData.length; i++)
{
if (!(splitData[i] == null) || !(splitData[i].length() == 0))
{
smallerArray.add(splitData[i].trim());
}
}
}
The reason I need to do this is that I am creating an app for a school project that reads questions from a delimited text file. I have a loop earlier that reads one line at a time from the text. I will insert that string into this program.
How do I make the ArrayList smallerArray a separate ArrayList everytime it goes through this method?
I need this so I can have an ArrayList of each of these ArrayList
Here is a sample code of what you intend to do -
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class SimpleFileReader {
private static final String DELEMETER = ":";
private String filename = null;
public SimpleFileReader() {
super();
}
public SimpleFileReader(String filename) {
super();
setFilename(filename);
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public List<List<String>> getRowSet() throws IOException {
List<List<String>> rows = new ArrayList<>();
try (Stream<String> stream = Files.lines(Paths.get(filename))) {
stream.forEach(row -> rows.add(Arrays.asList(row.split(DELEMETER))));
}
return rows;
}
}
And, here is the JUnit test for the above code -
import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.util.List;
import org.junit.jupiter.api.Test;
public class SimpleFileReaderTest {
public SimpleFileReaderTest() {
super();
}
#Test
public void testFileReader() {
try {
SimpleFileReader reader = new SimpleFileReader("c:/temp/sample-input.txt");
List<List<String>> rows = reader.getRowSet();
int expectedValue = 3; // number of actual lines in the sample file
int actualValue = rows.size(); // number of rows in the list
if (actualValue != expectedValue) {
fail(String.format("Expected value for the row count is %d, whereas obtained value is %d", expectedValue, actualValue));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Print all content from multiple files in directory

I have the following code seen below, this code looks through a directory and then prints all of the different file names. Now my question is, how would I go about changing my code, so that it would also print out all of the content within the files which it finds/prints? As an example, lets say the code finds 3 files in the directory, then it would print out all the content within those 3 files.
import java.io.File;
import java.io.IOException;
public class EScan {
static String usernamePc = System.getProperty("user.name");
final static File foldersPc = new File("/Users/" + usernamePc + "/Library/Mail/V2");
public static void main(String[] args) throws IOException {
listFilesForFolder(foldersPc);
}
public static void listFilesForFolder(final File foldersPc) throws IOException {
for (final File fileEntry : foldersPc.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
}
I tested it before posting. it is working.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* #author EdwinAdeola
*/
public class TestPrintAllFiles {
public static void main(String[] args) {
//Accessing the folder path
File myFolder = new File("C:\\Intel");
File[] listOfFiles = myFolder.listFiles();
String fileName, line = null;
BufferedReader br;
//For each loop to print the content of each file
for (File eachFile : listOfFiles) {
if (eachFile.isFile()) {
try {
//System.out.println(eachFile.getName());
fileName = eachFile.getAbsolutePath();
br = new BufferedReader(new FileReader(fileName));
try {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException ex) {
Logger.getLogger(TestPrintAllFiles.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(TestPrintAllFiles.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
You may use Scanner to read the contents of the file
try {
Scanner sc = new Scanner(fileEntry);
while (sc.hasNextLine()) {
String s = sc.nextLine();
System.out.println(s);
}
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
You can try one more way if you find suitable :
package com.grs.stackOverFlow.pack10;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;
public class EScan {
public static void main(String[] args) throws IOException {
File dir=new File("C:/your drive/");
List<File> files = Arrays.asList(dir.listFiles(f->f.isFile()));
//if you want you can filter files like f->f.getName().endsWtih(".csv")
for(File f: files){
List<String> lines = Files.readAllLines(f.toPath(),Charset.defaultCharset());
//processing line
lines.forEach(System.out::println);
}
}
}
Above code can me exploited in number of ways like processing line can be modified to add quotes around lines as below:
lines.stream().map(t-> "'" + t+"'").forEach(System.out::println);
Or print only error messages lines
lines.stream().filter(l->l.contains("error")).forEach(System.out::println);
Above codes and variations are tested.

Reading numbers from a file and creating an array (java)

I cannot figure out how to make this txt file with numbers into an array, I am able to get it to read and print the screen but I need to be able to organize the numbers and delete the duplicates. This is what my code looks like so far
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class File {
public static void main(String[] args) {
String filename = "C:/input.txt";
File rfe = new File();
rfe.readFile(filename);
}
private void readFile(String name) {
String input;
try (BufferedReader reader = new BufferedReader(new FileReader(name))) {
while((input = reader.readLine()) != null) {
System.out.format(input); // Display the line on the monitor
}
}
catch(FileNotFoundException fnfe) {
}
catch(IOException ioe) {
}
catch(Exception ex) { // Not required, but a good practice
}
}
}
I would recommend using an ArrayList rather than an Array.
With an array you would have to parse through the list and calculate the line count before you could even initialize it. An ArrayList is much more flexible as you don't have to declare how many values will be added to it.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class File {
private List<Integer> data = new ArrayList<Integer>(); //Create ArrayList
public static void main(String[] args) {
String filename = "C:/input.txt";
File rfe = new File();
rfe.readFile(filename);
}
private void readFile(String name) {
String input;
try (BufferedReader reader = new BufferedReader(new FileReader(name))) {
while((input = reader.readLine()) != null) {
data.add(Integer.parseInt(input));//Add each parsed number to the arraylist
System.out.println(input); // Display the line on the monitor
}
}
catch(FileNotFoundException fnfe) {
}
catch(IOException ioe) {
}
catch(Exception ex) { // Not required, but a good practice
ex.printstacktrace(); //Usually good for general handling
}
}
}

Categories