How do use console to choose any file from a folder? - java

I need to be able to choose any file inside a folder by input on console.
Code
Instead of a predefined like "bridge_rgb.png" I want to be able to choose any file in the folder via console input.
private void imageName() {
System.out.println("Select your image");
String input = scanner.next();
if (input.equals("bridge_rgb.png")) {
} else if (input.equals("gmit_rgb.png")) {
}
System.out.println("Image Selected");
}
Inside my functions I want to do the same, here's the code:
File file = new File("bridge_rgb.png");
BufferedImage source = ImageIO.read(file);
// processing: result gets created
File output = new File("bridge_grey.png");
ImageIO.write(result, "png", output);
I know a GUI would make file-choosing easy, but I have to use specifically a console.

Say you have specified a folder, or use the current working directory.
At least you need two ingredients:
a function which lists all files given in the folder as option to choose from
a user-interface (text-based or graphical) that allows to present those options and let the user choose from them (e.g. by hitting a number of clicking an item from a drop-down-list
List files in current directory
Search for [java] list files in directory and pick:
File[] files = directory.listFiles();
Text-based UI (TUI) to choose option by number
E.g. from How can I read input from the console using the Scanner class in Java?
// output on console
System.out.println("Choose from following files:");
for (int i=0, i < files.length(), i++) {
System.out.println(String.format("[%d] %s", i, file.getName());
}
// reading the number
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
// testing if valid, within options index (0..n)
if (i < 0 || i >= files.length()) {
System.out.println("Invalid input. Please enter a number from options.");
}
// file choosen
System.out.println("Your choice: " + file[i].getName());
// other UI operations, like display file, etc.
// IMPORTANT: always close the stream/scanner when finished
scanner.close();

Related

How to insert files as arguments

I am trying to pass in two text files as arguments but my program cannot find them. The files that i am trying to pass in are located in the same file as my project but is not inside my project folder. Image of file configuration.
I have tried entering the text files as, "../COSC485_P1_DFA.txt" "../COSC485_P1_Strings.txt"
if(args.length != 2){
System.out.println("ERROR, input agrument is incorrect. Please try again");
System.exit(0);
}
File automataFile = new File(args[0].substring(1, args[0].length() - 1));
File stringFile = new File(args[1].substring(1, args[1].length() - 1));
if(automataFile.exists()== false){
System.out.println("automata file doesnt exist");
}
if(stringFile.exists()== false){
System.out.println("string file doesnt exist");
System.exit(0);
}
The two if statements at the end of the code I provided should not do the print out statements. Right now they are printing out meaning the program cannot find the two files.

Java Scanning 2 Files and second file not found

Ok I am having a HUGE problem. I"m a Senior in College and this is my Senior project I'm working on in order to graduate so your help will be GREATLY appreciated.
I am having a problem with a scanner reading a file. Here is my method.
//This sets the text file to scan which is the List of all Employees ID number and Name only
try {
File file = new File("ListemployeeIDandName.txt");
scan = new Scanner(file);
}
catch (Exception e)
{
System.out.println("Could not find file: "+" ListemployeeIDandName.txt");
}
//First I need to get each employees name so this loop cycles through the file and loads the ID and name into a List
//Odd indexes will be the name of employee and Even will be the ID number
while(scan.hasNext())
{
Listemployeenames.add(scan.next());
}
//scan.reset();
//scan.close();
scanfile = scan.reset();
//Now that I have the List of all employees ID and names...I just want the names so I can search for the respective files
//This method will make a temp list of ONLY employee names by making a list of only the ODD indexes which are the names
LinkedList<String> List_names = new LinkedList<String>();
for(int y = 0;y<Listemployeenames.size();y++)
{
//this means if y is an even number than do nothing otherwise if its ODD add the index to the list
if((y%2) == 0)
{
}
else
{
List_names.add(Listemployeenames.get(y));
}
}
for(int z = 0;z<List_names.size();z++)
{
System.out.println(List_names.get(z));
}
//OK so now that I have the names of all the employees I need to use their names to find their file and load all their info to a the main list
String filepath = "";
for(int a = 0;a<List_names.size();a++)
{
//Ok so this will grab each bio file and send to the Employee Constructor which will set all the data from the file
try {
filepath = List_names.get(a)+"bio.txt";
File file2 = new File(filepath);
scanfile = new Scanner(file2);
}
catch (FileNotFoundException e)
{
System.out.println("Could not find file: "+filepath);
}
finally{
//scanfile.close();
//scan.reset();
}
//this method sends the scanner file to that employee and sets their data
List_AllEmployees.add(new Employee(scanfile));
}
Now this method READS from 2 files...and THEY DO EXIST the first file at the top of the method is working fine ...but for some reason the 2nd file cannot be found even though it does exist.
Now here is where it gets wierd...soo...both files are in the java default...so I tried something wierd...since I know the second files do exist but for some reason scanner can't find them i decided to simply use file explorer and go to the directory where it is and cut and paste it to another directory then immediatly cut and paste it back into the java default directory...i ran the method again AND THEN IT WORKS...
My question is wtf? Why did java scanner recognize the file after I simply cut and pasted it back into its default directory? and how come the first file is working with no problem but the 2nd file needs to manually be placed into the default folder? please help this is my first time using this site so I don't know how to paste my code other than in here. Thanks for your help.

Case study: Is this an effective way to split a file?

So om working my way trough a task in my java-course at school. For better understanding of what the code is supposed to do ill quote it:
"(Split files) Suppose you want to back up a huge file(e.g., a 10-GB AVI file) to a CD-R. You can achieve it by splitting the file into smaller pieces and backing up these pieces separately. Write a utility program that splits a large file into smaller ones using the following command: java ClassName SourceFile numberOfPieces
The command creates the files SourceFile.1, SourceFile2...etc
Now to be clear. This post is in no way an attempt to get a "solution" for the problem. I have solved it (with what i know). And i merely want to get more enlightned on some matters that crossed my mind when writing the code.
Is it neccesary to create a new output for every single file im
copying to? Doesn`t this demand unneccesary system power?
The first file that gets copied(SourceFile is in this case a .png
file) is possible to view. And show a fraction of the original
picture. (If i split into two. i can view half the picture.) But
the latter ones i cant view.. Why is that?
Is it possible to reassemble the splitted files in any way? if my
pictures was split into two files, can i put them back together and
view the whole picture?
The code, if you want to look at it.
All feedback is welcome,
Have a good day! :)
package oblig2;
import java.io.*;
import java.util.*;
public class Test {
/**
* Main method
*
* #param args[0] for source file
* #param args[1] for number of pieces
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// The program needs to be executed with two parameters in order to
// work. This sentence check for it.
if (args.length != 2) {
System.out.println("Usage: java Copy sourceFile numberOfPieces");
System.exit(1);
}
// Check whether or not the sourcefile exists
File sourceFile = new File(args[0]);
if (!sourceFile.exists()) {
System.out.println("Source file " + args[0] + " does not exist");
System.exit(2);
}
// Need an Array to store all the new files that is supposed to contain
// parts of the original file
ArrayList<File> fileArray = new ArrayList<File>();
// All the new files need their own output(or do they?)
ArrayList<BufferedOutputStream> outputArray = new ArrayList<BufferedOutputStream>();
// Using randomAccessFile on the sourcefile to easier read parts of it
RandomAccessFile inOutSourceFile = new RandomAccessFile(sourceFile,
"rw");
// This loop changes the name for the new files, so they match the
// sourcefile with an appended digit
for (int i = 0; i < Integer.parseInt(args[1]); i++) {
String nameAppender = String.valueOf(i);
String nameBuilder;
int suffix = args[0].indexOf(".");
nameBuilder = args[0].substring(0, suffix);
fileArray.add((new File(nameBuilder + nameAppender + ".dat")));
}
// Here i create the output needed for all the new files
for (int i = 0; i < Integer.parseInt(args[1]); i++) {
outputArray.add(new BufferedOutputStream(new FileOutputStream(
new File(fileArray.get(i).getAbsolutePath()))));
}
// Now i determine in how many parts the sourcefile needs to be split,
// and the size of each.
float size = inOutSourceFile.length();
double parts = Integer.parseInt(args[1]);
double partSize = size / parts;
int r, numberOfBytesCopied = 0;
// This loop actually does the job of copying the parts into the new
// files
for (int i = 1; i <= parts; i++) {
while (inOutSourceFile.getFilePointer() < partSize * i) {
r = inOutSourceFile.readByte();
outputArray.get(i - 1).write((byte) r);
numberOfBytesCopied++;
}
}
// Here i close the input and outputs
inOutSourceFile.close();
for (int i = 0; i < parts; i++) {
outputArray.get(i).close();
}
// Display the operations
System.out.println(args[0] + " Has been split into " + args[1]
+ " pieces. " + "\n" + "Each file containig " + partSize
+ " Bytes each.");
}
}
Of course it is necessary to open all output files. But you don't have to open them at all times. You can open the first file, write to it, close it, open the second file, write to it, close it, etc.
File format, .png for example, have a structure that have to follow. It may have special header, and may have special footer. That's why when this file split into two or more, the first will lose its footer, the middle will lose its header and footer, and the last will lose it's header. This make them unusable as individual file.
Of course it is possible. By combining back all the parts, the original file fill be restructured.

Text input and output java

I am trying to read 2 files after i read the files i want to get their contents and manipulate the contents of the two files then update a new file which is the output. The files are in the same folder as the program but the program always throws a FileNotFoundException.
Below is my code:-
import java.io.*;
import java.util.Scanner;
public class UpdateMaster {
public static void main(String[] args)
{
String master = "Customer.dat";
String trans = "Transactns.dat";
String newMaster = "Temp.txt";
Scanner inputStreamMaster = null;
Scanner inputStreamTrans = null;
PrintWriter inputStreamNewMaster = null;
try
{
inputStreamMaster = new Scanner(new File(master));
inputStreamTrans = new Scanner(new File(trans));
inputStreamNewMaster = new PrintWriter(newMaster);
}
catch(FileNotFoundException e)
{
System.out.println("Error: you opend a file that does not exist.");
System.exit(0);
}
catch(IOException e)
{
System.out.println("Error.");
System.exit(0);
}
do
{
String transLine = inputStreamTrans.nextLine();
String masterLine = inputStreamMaster.nextLine();
String[] transLineArr = transLine.split(",");
String[] masterLineArr = masterLine.split(",");
int trAccNo = Integer.parseInt(transLineArr[0]);
int sales = Integer.parseInt(transLineArr[1]);
int masterAccNo = Integer.parseInt(masterLineArr[0]);
int balance = Integer.parseInt(masterLineArr[1]);
while(masterAccNo== trAccNo){
inputStreamNewMaster.println(trAccNo+ " , "+masterAccNo);
masterLine = inputStreamMaster.nextLine();
masterLineArr = masterLine.split(",");
masterAccNo = Integer.parseInt(masterLineArr[0]);
balance = Integer.parseInt(masterLineArr[1]);
}
balance = balance + sales;
inputStreamNewMaster.println(masterAccNo+ " , "+balance);
}while(inputStreamTrans.hasNextLine());
inputStreamMaster.close();
inputStreamTrans.close();
inputStreamNewMaster.close();
//System.out.println(" the line were written to "+ newMaster);
}
}
Like #Ankit Rustagi said in the comments, you need the full path of the files if you want to keep the current implementation.
However, there is a solution where you only need the file names: use BufferedReader / BufferedWriter. See here an example on how to use these classes (in the example it uses the full path but it works without it too).
Use absolute path
String master = "C:/Data/Customer.dat";
String trans = "C:/Data/Transactns.dat";
String newMaster = "C:/Data/Temp.txt";
The code works for me, i guess you misspelled some filename(s) or your files are in the wrong folder. I created your files on the same level as the src or the project. Also this is the folder where the files are exspected.
There's nothing wrong with using relative paths like tihis. What's happening is that your program is looking for the files in the directory where you execute the program, which doesn't have to be the folder of the program. You can confirm this by logging the absolute path of the files before you try to read them. For example:
File masterFile = new File(master);
System.out.printf("Using master file '%s'%n", masterFile.getAbsolutePath());
inputStreamMaster = new Scanner(masterFile);
In general you should not hardcode file paths but allow the user to specify them in someway, for example using command line arguments, a configuration file with a well known path, or an interactive user interface.
There is a way to locate the program's class file but it's a little tricky because Java allows classes to be loaded from compressed archives that may be located in remote systems. It's better to solve this problem in some other manner.
Try this:
String current = new java.io.File( "." ).getCanonicalPath();
System.out.println("I look for files in:"+current);
To see what directory your program expects to find its input files. If it shows the correct directory, check spelling of filenames. Otherwise, you have a clue as to what's gone wrong.

how to read a text file using scanner in Java?

This is my code to read a text file. When I run this code, the output keeps saying "File not found.", which is the message of FileNotFoundException. I'm not sure what is the problem in this code.
Apparently this is part of the java. For the whole java file, it requires the user to input something and will create a text file using the input as a name.
After that the user should enter the name of the text file created before again (assume the user enters correctly) and then the program should read the text file.
I have done other parts of my program correctly, but the problem is when i enter the name again, it just can not find the text file, eventhough they are in the same folder.
public static ArrayList<DogShop> readFile()
{
try
{ // The name of the file which we will read from
String filename = "a.txt";
// Prepare to read from the file, using a Scanner object
File file = new File(filename);
Scanner in = new Scanner(file);
ArrayList<DogShop> shops = new ArrayList<DogShop>();
// Read each line until end of file is reached
while (in.hasNextLine())
{
// Read an entire line, which contains all the details for 1 account
String line = in.nextLine();
// Make a Scanner object to break up this line into parts
Scanner lineBreaker = new Scanner(line);
// 1st part is the account number
try
{ int shopNumber = lineBreaker.nextInt();
// 2nd part is the full name of the owner of the account
String owner = lineBreaker.next();
// 3rd part is the amount of money, but this includes the dollar sign
String equityWithDollarSign = lineBreaker.next();
int total = lineBreaker.nextInt();
// Get rid of the dollar sign;
// we use the subtring method from the String class (see the Java API),
// which returns a new string with the first 'n' characters chopped off,
// where 'n' is the parameter that you give it
String equityWithoutDollarSign = equityWithDollarSign.substring(1);
// Convert this balance into a double, we need this because the deposit method
// in the Account class needs a double, not a String
double equity = Double.parseDouble(equityWithoutDollarSign);
// Create an Account belonging to the owner we found in the file
DogShop s = new DogShop(owner);
// Put money into the account according to the amount of money we found in the file
s.getMoney(equity);
s.getDogs(total);
// Put the Account into the ArrayList
shops.add(s);
}
catch (InputMismatchException e)
{
System.out.println("File not found1.");
}
catch (NoSuchElementException e)
{
System.out.println("File not found2");
}
}
}
catch (FileNotFoundException e)
{
System.out.println("File not found");
} // Make an ArrayList to store all the accounts we will make
// Return the ArrayList containing all the accounts we made
return shops;
}
If you are working in some IDE like Eclipse or NetBeans, you should have that a.txt file in the root directory of your project. (and not in the folder where your .class files are built or anywhere else)
If not, you should specify the absolute path to that file.
Edit:
You would put the .txt file in the same place with the .class(usually also the .java file because you compile in the same folder) compiled files if you compile it by hand with javac. This is because it uses the relative path and the path tells the JVM the path where the executable file is located.
If you use some IDE, it will generate the compiled files for you using a Makefile or something similar for Windows and will consider it's default file structure, so he knows that the relative path begins from the root folder of the project.
Well.. Apparently the file does not exist or cannot be found. Try using a full path. You're probably reading from the wrong directory when you don't specify the path, unless a.txt is in your current working directory.
I would recommend loading the file as Resource and converting the input stream into string. This would give you the flexibility to load the file anywhere relative to the classpath
If you give a Scanner object a String, it will read it in as data. That is, "a.txt" does not open up a file called "a.txt". It literally reads in the characters 'a', '.', 't' and so forth.
This is according to Core Java Volume I, section 3.7.3.
If I find a solution to reading the actual paths, I will return and update this answer. The solution this text offers is to use
Scanner in = new Scanner(Paths.get("myfile.txt"));
But I can't get this to work because Path isn't recognized as a variable by the compiler. Perhaps I'm missing an import statement.
This should help you..:
import java.io.*;
import static java.lang.System.*;
/**
* Write a description of class InRead here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class InRead
{
public InRead(String Recipe)
{
find(Recipe);
}
public void find(String Name){
String newRecipe= Name+".txt";
try{
FileReader fr= new FileReader(newRecipe);
BufferedReader br= new BufferedReader(fr);
String str;
while ((str=br.readLine()) != null){
out.println(str + "\n");
}
br.close();
}catch (IOException e){
out.println("File Not Found!");
}
}
}
Just another thing... Instead of System.out.println("Error Message Here"), use System.err.println("Error Message Here"). This will allow you to distinguish the differences between errors and normal code functioning by displaying the errors(i.e. everything inside System.err.println()) in red.
NOTE: It also works when used with System.err.print("Error Message Here")

Categories

Resources