Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: Giving Java the name of a file to be read via command line?

  1. #1
    Junior Member
    Join Date
    Oct 2010
    Posts
    12
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Giving Java the name of a file to be read via command line?

    (I hope this is the right place to post my question!)

    So I finally finished a program for my class, but I realized that I had been feeding java the file directly inside of the code, but the assignment requires that the name of the file be given on the command line. I finally got command prompt to work on my computer (running windows vista), but I don't quite know how to let java know that the name of the text file to be read will be provided via command line. This is the first time I've ever had to deal with command line arguments so I'm a little confused. I'll include my code below. The file that is currently to be read is sampleinput1.txt.

    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import java.io.FileWriter;
     
    public class Homework2{
     
    	public static final int ROWS = 10;        //you may change this value
    	public static final int COLS = 7;        //you may change this value
    	public static final int SIZE = 85;        //you may change this value
    	public static final int WAIT = 100;        //you may change this value.
    	public static final Color IDENTCOLOR = Color.WHITE;
    	public static final String[] identifiers = {"charname", "V_VS_DV", "SHOES","INVIS_FLY", "LIFE_FREE",
                                "COLSANDERS","VEY_APOLLO","LAK_CELTIC","CS_MAJOR","SMILE","LOVEFIRST"};
     
    	public static void main(String[] args)throws FileNotFoundException {
    		File inFile = new File("C:/Users/Irena/Desktop/Homework2/sampleinput2.txt");
    		Scanner scanner;
     
    		try {
    			scanner = new Scanner(inFile);
    		} catch (Exception e){
    			System.err.println("File not found: " + e.toString());
    			return;
    		}
     
    		Mosaic.open(ROWS,COLS,SIZE,SIZE);//Opens Canvas
    		labelQuestions();//Labels Questions
    		getAnswers(scanner);//Reads Text Files For Information
    		exportCSVFile(scanner);//Exports Information As A CSV File
     
    	}//end of main
     
     
    		//Method:			labelQuestions
    		//Input:				N/A
    		//Called by:		main
    		//Purpose:			This sends the question identifiers to the Mosaic canvas, 
    		//						labeling them in their appropriate spots.
     
    		public static void labelQuestions(){
    			for(int i = 1; i <= ROWS; i++){
    				Mosaic.drawLabel(i-1, 0, identifiers[i], IDENTCOLOR);
    			}
    		}//End of labelQuestions
     
    		//Method:			getAnswers
    		//Input:				Scanner scanner
    		//Called by:		main		
    		//Purpose:			This methods reads through the inputed textfile for lines that 
    		//						contain colons. It then splits the Strings along the colon character. 
    		//						It then organizes this information into array lists so that each array 
    		//						lists the character and the numerical value of each vote cast by that character.  
     
    		public static void getAnswers(Scanner scanner){
    			ArrayList<String[]> userSurveyData = new ArrayList<String[]>();
    			String[] userTempSurveyData = new String[11];
     
    			while(scanner.hasNextLine()){ 
    				String[]  line = scanner.nextLine().split(": ");
    				for(int i = 0; i < identifiers.length; i++){
    					if(line[0].equals(identifiers[i]) && !line[1].equals("")){
    						userTempSurveyData[i] = line[1]; 
    						colorAnswers(userTempSurveyData[0],userTempSurveyData[i],i-1);										
    					}
    				}
    				if (line[0].equals("request") && line[1].equals("Submit the survey"))  {
    					userSurveyData.add(userTempSurveyData); 
    					System.out.println();
    					for (int j=0; j < 10; j++)
    						userTempSurveyData[j] = "";
    					}
    				}
    		}//End of getAnswers
     
    		//Method:			colorAnswers
    		//Input:				String Name, String Answer, int i
    		//Called by:		getAnswers
    		//Purpose:			This methods gets the name of the respondant, the numberical 
    		//						answer and the row number and then sends all of that information 
    		//						to the appropriate method that will send the data to the 
    		//						Mosaic canvas to visually represent the data.  
     
    		public static void colorAnswers(String Name, String Answer, int i){
    			if(Answer.equals("5")){
    				colorIntensity(i,1,Name);
    			}
    			if(Answer.equals("4")){
    				colorIntensity(i,2,Name);
    			}
    			if(Answer.equals("3")){
    				colorIntensity(i,3,Name);
    			}
    			if(Answer.equals("2")){
    				colorIntensity(i,4,Name);
    			}          
    			if(Answer.equals("1")){
    				colorIntensity(i,5,Name);
    			}
    			if(Answer.equals("0")){
    				colorIntensity(i,6,Name);            
    			}      
    			Mosaic.delay(WAIT);      
    		}//End of colorAnswers
     
    		//Method:			colorIntensity
    		//Input:				int i, int j, String Name
    		//Called by:		colorAnswers
    		//Purpose:			This method gets data from colorAnswers and sends that information 
    		//						to the proper location on the Mosaic. This method is also in change 
    		//						for increasing the opacity of an answer as more and more people vote 
    		//						for that option. 
     
    		public static void colorIntensity(int i, int j, String Name){
    			Mosaic.getBlue(i,j);
    			Mosaic.setColor(i, j, 0, 0, Mosaic.getBlue(i,j)+2);
    			Mosaic.drawLabel(i, j, Name, IDENTCOLOR);
    		}//End of colorIntensity
     
    		//Method:			exportCSVFile
    		//Input:				Scanner scanner
    		//Called by:		main
    		//Purpose:			This method writes pertinent data to a csv file, naming the 
    		//						file according to what the user inputs when prompted. 
     
    		public static void exportCSVFile(Scanner scanner){
     
    			Scanner scan = new Scanner(System.in); 
    			String[] results = {"","", "", "", "", "", "", "", "", "", ""};
     
    			System.out.print("Please enter the output file name:\t"); 
          	String message = scan.nextLine(); 
    			while(scanner.hasNextLine()){
    				String[] line = scanner.nextLine().split(": ");
    				for(int i = 0; i < identifiers.length; i++){
    				if(line[0].equals(identifiers[i])){
    					if(!(results[i].equals("")))
    						results[i] += ", ";
    						results[i] += line[1];
    					}
    				}
    			}
    		try{
    			FileWriter writer = new FileWriter(message);
    			writer.append("question identifier,strongly agree,agree,no opinion,disagree,strongly disagree,N/A or decline,");	
    			for(int i = 1; i < identifiers.length; i++){
    				writer.append(identifiers[i]+","+results[i]+",");
    			}
    			writer.flush();
    			writer.close();
    		}
    		catch(IOException e){
    			e.printStackTrace();
    		}   
    	}//End of exportCSVFile
    }//End of Homework2

    I figure that anything written after "java Homework2" in the command prompt will be sent to the program as String[] args, but as to what to do with args to make the program run correctly, I'm not entirely sure how to proceed. Any help you can give me is really appreciated!


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Giving Java the name of a file to be read via command line?

    See that argument you're passing into your main method? That's an array of the command-line arguments being passed to your program. So, if your program only takes one file name as the argument, that would be the parameter you should pass.

    public static void main(String[] args)
    {
        File inFile = new File(args[0]); // assumes file is passed as the first command-line argument. No error checking is done.
        // ... other code
    }

  3. The Following User Says Thank You to helloworld922 For This Useful Post:

    lavloki (October 14th, 2010)

  4. #3
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    495
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Giving Java the name of a file to be read via command line?

    And if the filename/path that you pass from the command line contains spaces, enclose it in double quotes.

    db

  5. The Following User Says Thank You to Darryl.Burke For This Useful Post:

    lavloki (October 14th, 2010)

  6. #4
    Junior Member
    Join Date
    Oct 2010
    Posts
    12
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Giving Java the name of a file to be read via command line?

    Thank you very much! That seems to have solved my problem!

  7. #5
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 287 Times in 225 Posts
    Blog Entries
    4

    Default Re: Giving Java the name of a file to be read via command line?

    I have marked this thread as solved You can do this yourself from the Thread Tools menu at the top.
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

    Looking for a Java job? Visit - Java Programming Careers

Similar Threads

  1. A problem with command line compilation
    By goodguy in forum Java Theory & Questions
    Replies: 4
    Last Post: August 2nd, 2010, 11:58 AM
  2. [SOLVED] Command Line Argument Help
    By EmSaint in forum Loops & Control Statements
    Replies: 2
    Last Post: January 28th, 2010, 10:55 AM
  3. Java program to read last line of a file
    By JavaPF in forum File Input/Output Tutorials
    Replies: 2
    Last Post: September 10th, 2009, 03:26 AM
  4. Reading a file line by line using the Scanner class
    By JavaPF in forum File Input/Output Tutorials
    Replies: 0
    Last Post: April 17th, 2009, 08:34 AM
  5. How to Read a file line by line using BufferedReader?
    By JavaPF in forum File Input/Output Tutorials
    Replies: 0
    Last Post: May 19th, 2008, 07:32 AM

Tags for this Thread