reading filename through command line argument - java

I came across the following code in a book recently. It says that we can reference a file for instance that we want to read by writing a command line like the first line below. However it is throwing an error with this line. Can someone please advise as I have never come across this before?
Thanks
java ShowFile c:/Users/Bosra/Desktop/Sample.txt
import java.io.*;
public class ShowFile
{
public static void main(String args[])
{
int i;
FileInputStream fin;
//first confirm that a filename has been specified
if(args.length!=1)
{
System.out.println("Usage:ShowFile Filename");
return;
}
}
}

The first line is the thing you should type in at the command line after compiling the file - it doesn't belong in the file itself.

Related

Receive input from method using File IO (Java)

I need to allow the user to tell the program where the file is and output that data in a particular way. I cannot seem to pass the data to the separate class file. What am I doing wrong?
import java.util.Scanner;
import java.io.*;
public class Student_Test {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in); // sets up scanner
System.out.print("Enter file name: "); //user provides file name and location
String userFile = in.nextLine(); // accepts input from user
File file = new File(userFile); //uses the file method to import the data
Scanner inputFile = new Scanner(file); // uses scanner to read the data
System.out.print(inputFile.Out());
}
}
Also can I have some tips on how to start a separate Student class to do the work. The file that I'll be reading in has multiple lines of text. I will have to take some of that text and convert it into integers. Then I have to output it in a certain way. Should I use a void method or a return method?
Just a few tips
First you have to think what attributes a Student class needs.For example:
A student has a full name ,a social security number (maybe?)
Then you can create something like this as a seperate class
public class Student {
private String fullName,socialSecurityNumber;
public Student(String fullname,String secNumb){
fullName=fullname;
socialSecurityNumber=secNumb;
}
}
But mostly you have to think of what the student class has to do .
I've just been working a bit with file processing myself. Still learning the basic concepts of java and to my level I found this tutorial quite helpful: http://www.functionx.com/java/Lesson23.htm.
It goes through how you create, save, open and read from a file.
As seen in the tutorial one way to output the contents of your file would be to save each line to a variable. Assuming that you know what information is placed on each line this will give you some flexibility in regard to how you want to present the file contents. You can use the nextLine() for that as well. You can do this in a while loop, which reads every line in the file.
while(inputFile.hasNext()){
String studentName = inputFile.nextLine();
String studentCourse = inputFile.nextLine();
}
The hasNext() returns true until the Scanner gets to the end of the file and there are no more lines to read.
If you want to print your file contents to the console you can probably then use a void method as it doesn't require you to return anything.

Java System.out.println() throwing error

So I'm coming back to Java after a long time of not working with it. First method of my first class and I'm seeing an error I've never seen before.
For every System.out.println() statement I have, the .out. part throws this error:
cannot find symbol
symbol: variable out
location: class System
my class is unfinished but looks like this
import java.io.*;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class System{
//Variables
char map[];
/*
Functions
FILE INPUT
*/
public static void ReadFile(){
FileInputStream fstream;
try{
fstream = new FileInputStream("C:\\Users\\James\\Documents\\NetBeansProjects\\Assignment1\\src\\testfiles");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
System.out.println("Your Input File");
System.out.println("****************");
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
// Print the content on the console
System.out.println(strLine);
inputArray.add(strLine);
}
System.out.println("****************");
//Close the input stream
br.close();
System.out.println();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
Every single .out. in this block of code throws this error :cannot find symbol
symbol: variable out
location: class System
I am using Netbeans8.0.2 and java 1.7.0_76(because I have to)
Can someone shed some light on this?
This is the problem:
public class System
You're creating your own class called System, so when you later use:
System.out.println
that's looking in your System class rather than java.lang.System.
Options:
Change the name of your class. It's generally a bad idea to create classes with the same name as classes within java.lang, precisely for this reason
Fully-qualify the call:
java.lang.System.out.println(...);
I'd pick the former option, personally.
Replace all the System.<something> with java.lang.System.<something>.
In its current state, your code is referencing your own System class. Since the name is the same, and yours has a higher priority in the scope, you end up with this error.
It's probably a better idea to change the name of your class. You generally don't want to conflict with internal names.
When you are using System.out.println() in the same class name System . So at the time of calling method println() your program searching the method in same class instead of checking same in java.lang. package.
So as for the solution of issue , either you can change the name of class to some thing else rather than System or you can change System.out.println() with java.lang.System.out.println().

FileNotFoundException when creating a Scanner in Eclipse with Java

I'm getting a FileNotFoundException when running the following Java 6 code on Eclipse (Indigo) on Snow Leopard:
import java.io.*;
import java.util.*;
public class readFile {
public static void main(String[] args) {
Scanner s = new Scanner(new FileReader("/Users/daniel/pr/java/readFile/myfile.txt")); // Line 9
}
}
The exception is
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type FileNotFoundException
at readFile.main(readFile.java:9)
My current workspace is /Users/daniel/pr/java. It contains only one project (readFile), and the file hierarchy looks like this:
- readFile
- src
- (default package)
- readFile.java
- JRE System Library [JavaSE-1.6]
- myfile.txt
After reading several very similar questions, I've tried
placing copies of myfile.txt in the project, bin, src, and workspace directories, as well as my home and root folders
identifying the working directory and using a relative path
manually setting the workspace via "Run Configurations > Arguments > Working Directory" in Eclipse
running the program with the command line Java launcher in the bin, readFile, src, and java directories (with copies of myfile.txt in all of these places)
removing the file extension and/or lengthening the filename (above some supposed minimum character limit), and
verifying the permissions of myfile.txt (they're now rw-r--r--).
I'm at a loss. What could be the problem? (Thank you for reading!)
The exception tells you the problem.
The code you have in your main might throw a FileNotFoundException, so you need to consider that in your code, either by declaring in the method signature that that exception can be thrown, or by surrounding the code with a try catch:
Declaring:
public static void main(String[] args) throws FileNotFoundException{
Scanner s = new Scanner(new FileReader("/Users/daniel/pr/java/readFile/myfile.txt")); // Line 9
}
Or using try/catch
public static void main(String[] args) {
try {
Scanner s = new Scanner(new FileReader("/Users/daniel/pr/java/readFile/myfile.txt")); // Line 9
} catch (FileNotFoundException e) {
//do something with e, or handle this case
}
}
The difference between these two approaches is that, since this is your main, if you declare it in the method signature, your program will throw the Exception and stop, giving you the stack trace.
If you use try/catch, you can handle this situation, either by logging the error, trying again, etc.
You might want to give a look at:
http://docs.oracle.com/javase/tutorial/essential/exceptions/ to learn about exception handling in Java, it'll be quite useful.
FileNotFoundException is a checked exception ! You must catch the exception ...
public static void main(String[] args) {
try {
Scanner s = new Scanner(new FileReader("/Users/daniel/pr/java/readFile/myfile.txt")); // Line 9
} catch(FileNotFoundException ex) {
//Handle exception code ...
}
}
"/Users/daniel/pr/java/readFile/myfile.txt"
Shouldn't that be:
"/users/daniel/pr/java/readFile/myfile.txt"

How to access inline text file using Java?

A program i am working on deals with processing file content. Right now i am writing jUnit tests to make sure things work as expected. As part of these tests, i'd like to reference an inline text file which would define the scope of a particular test.
How do i access such a file?
--
Let me clarify:
Normally, when opening a file, you need to indicate where the file is. What i want to say instead is "in this project". This way, when someone else looks at my code, they too will be able to access the same file.I may be wrong, but isn't there a special way, one can access files which are a part of "this" project, relative to "some files out there on disk".
If what you mean is you have a file you need your tests to be able to read from, if you copy the file into the classpath your tests can read it using Class.getResourceAsStream().
For an example try this link (Jon Skeet answered a question like this):
read file in classpath
You can also implement your own test classes for InputStream or what have you.
package thop;
import java.io.InputStream;
/**
*
* #author tonyennis
*/
public class MyInputStream extends InputStream {
private char[] input;
private int current;
public MyInputStream(String s) {
input = s.toCharArray();
current = 0;
}
public int read() {
return (current == input.length) ? -1 : input[current++];
}
#Override
public void close() {
}
}
This is a simple InputStream. You give it a string, it gives you the string. If the code you wanted to test required an InputStream, you could use this (or something like it, heh) to feed exactly the strings wanted to test. You wouldn't need resources or disk files.
Here I use my lame class as input to a BufferedInputStream...
package thop;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
*
* #author tonyennis
*/
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
InputStream is = new MyInputStream("Now is the time");
BufferedInputStream bis = new BufferedInputStream(is);
int res;
while((res = bis.read()) != -1) {
System.out.println((char)res);
}
}
}
Now, if you want to make sure your program parses the inputStream correctly, you're golden. You can feed it the string you want to test with no difficulty. If you want to make sure the class being tested always closes the InputStream, add a "isOpen" boolean instance variable, set it to true in the constructor, set it to false in close(), and add a getter.
Now your test code would include something like:
MyInputStream mis = new MyInputStream("first,middle,last");
classBeingTested.testForFullName(mis);
assertFalse(mis.isOpen());

Java FileReader error

Hi I'm a beginner of Java lauguage.
It seems like my computer does not recognize FileReader at all.(Random class does not work either.) I typed the exact same code in a different computer and it worked. I uninstalled JDK and reinstalled it, but still doesn't work. I don't know what to do.
My environment
Samsung Netbook N150 plus. ///
windows 7 starter///
java(1.6_21 standard edition) ///
jGrasp(1.8).
Here is my code.
import java.io.*;
import java.util.*;
public class FileReaderGG
{
public static void main(String[] args)throws Exception
{
FileReader infile = new FileReader("todolist.txt");
Scanner indata = new Scanner(infile);
while (indata.hasNextLine())
{
System.out.println(indata.nextLine());
}
infile.close();
}
}
It gives me errors saying "cannot find symbol"
Looks like this
FileReaderGG.java:11: cannot find symbol
symbol : constructor FileReader(java.lang.String)
location: class FileReader
FileReader infile = new FileReader("todolist.txt");
5 more errors are there. I spent a whole day trying to figure out what the problem is.
Please help me out.
It means that you are trying to use a constructor that isn't there. Apparently you are trying to input a String into the constructor, but there is no constructor that accepts just a String value, but that is not true for java.io.FileReader. Is there another class in the same package (folder) called "FileReader"? If so, line 8 should be
java.io.FileReader infile = new java.io.FileReader("todolist.txt");
instead. Other solutions include
public class FileReaderGG
{
public static void main(String[] args) throws Exception
{
String pathName = System.getProperty("user.dir") + (FileReaderGG.class.getPackage() == null ? "" : "\\" + FileReaderGG.class.getPackage().getName().replace('.', '\\'));
java.io.FileReader infile = new java.io.FileReader(pathName + "\\todolist.txt");
java.util.Scanner indata = new java.util.Scanner(infile);
while (indata.hasNextLine())
{
System.out.println(indata.nextLine());
}
infile.close();
}
}
Note how no imports are made and all packages are explicitly declared. This should work no matter what. Just so you know, line 5 gets (A) the path from which the program is being run (hopefully the same as the resource file) and (B) checks if it is in a package and adds the needed sub-folders (though, it seems you aren't in any so it probably isn't needed)
I think your code is 100% right. Its working on my end at least. Are u compiling this program from IDE or from command line?
I think you have to import more, here's what I mean:
import java.util.Scanner;
import java.util.Scanner.*;
import java.io.FileReader;
import java.io.FileReader.*;
You know that when you
import java.util.Scanner;
It only imports the "Scanner" package, but not other packages in the Scanner package.

Categories

Resources