Reading Text Files Java:15 Error: Cannot Find Symbol - java

Im trying to read the content from a text file. ReadTextFile.java and ReadTextFileTest.java are in the same package ReadTextFile. I am using 2 packages in one project, ReadTextFiles and CreateTextfiles. ReadTextFiles package reads content from a text file and CreateTextFile package inputs content into a text file.
When I get to the command prompt I try to compile the java file into a class file by javac ReadTextFileTest.java. I get the following error everytime.
ReadTextFileTest.java:15 error: cannot find symbol
ReadTextFile application = new ReadTextFile();
^
symbol: class ReadTextFile
location: class ReadTextFileTest
ReadTextFileTest.java:15 error: cannot find symbol
ReadTextFile application = new ReadTextFile();
^
symbol: class ReadTextFile
location: class ReadTextFileTest
11.2 errors
Im guessing its having trouble recognizing the object I created of the ReadTextFile.java class.
Here is the two classes I used:
ReadTextFile.java
package ReadTextFile;
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.IllegalStateException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import AccountRecord.AccountRecord;
public class ReadTextFile
{
private Scanner input;
public void openFile()
{
try
{
input = new Scanner( new File( "clients.txt" ) );
}
catch ( FileNotFoundException fileNotFoundException )
{
System.err.println( "Error opening file." );
System.exit(1);
}
}
public void readRecords()
{
AccountRecord record = new AccountRecord();
System.out.printf( "%-10s%-12s%-12s%10s\n", "Account",
"First Name", "Last Name", "Balance" );
try
{
while ( input.hasNext() )
{
record.setAccount( input.nextInt() );
record.setFirstName( input.next() );
record.setLastName( input.next() );
record.setBalance( input.nextDouble() );
System.out.printf( "%-10d%-12s%-12s%10.2f\n",
record.getAccount(), record.getFirstName(),
record.getLastName(), record.getBalance() );
}
}
catch ( NoSuchElementException elementException )
{
System.err.println( "File improperly formed." );
input.close();
System.exit( 1 );
}
catch ( IlegalStateException stateException )
{
System.err.println( "Error opening file." );
System.exit( 1 );
}
}
public void closeFile()
{
if ( input !=null )
input.close();
}
}
ReadTextFileTest.java
package ReadTextFile;
public class ReadTextFileTest
{
public static void main(String[] args)
{
ReadTextFile application = new ReadTextFile();
application.openFile();
application.readRecords();
application.closeFile();
}
}

Add import statement as below:-
package ReadTextFile;
import ReadTextFile;
public class ReadTextFileTest
{
public static void main(String[] args)
{
ReadTextFile application = new ReadTextFile();
application.openFile();
application.readRecords();
application.closeFile();
}
}

Remove
package ReadTextFile;
ReadTextFile is not a package but a class. Remove this line and try to compile again.
You must have meant
import readTextFile;
but if you make sure it is in the same directory, you don't have to import it. So, just delete the first line of ReadTextFileTest.
Edit after comment:
Generally, avoid naming packages with the same names as classes ( although as #Masud said in the comments it is possible). You should follow these naming conventions.

Related

How to get the class variables count of a given.java file?

I need to create an application to get the class variables(attributes) count on a given .java file.So I developed a code using java reflection as below.So in here I create a new .java file with the same content of importing .java file in my src package because then that .java file can be accessible to the reflection purposes.But the problem is IDE is not figuring out the updates of that files automatically,which means even though the file is created already in my directory IDE doesn't figure it out instantly so I need to refresh the src package to notify the updates to the IDE.So how can I solve this issue.Therefor when you run this for first time there will be an exception of class not found exception ,because even though that .java file already there in the src folder IDE doesn't know.
I tried with eclipse, Intelij IDES.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
importjava.util.concurrent.atomic.AtomicInteger;
public class AppInitializer {
public static void main(String args[])throws Exception{
AtomicInteger atomicInteger = new AtomicInteger();
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
try {
meth ();
} catch (ClassNotFoundException e) {
e.printStackTrace ( );
}
}
});
FileReader fr=new FileReader("C:\\Users\\User\\Desktop\\Sample.java");
int i;
StringBuffer str= new StringBuffer("");
while((i=fr.read())!=-1){
str.append ( (char)i );}
String s = String.valueOf ( str );
String replaceString=s.replaceAll ( "public class [^\\n]+", "public class filename{" );
System.out.println (replaceString );
fr.close();
try {
FileWriter myWriter = new FileWriter("src/filename.java");
myWriter.write( String.valueOf ( replaceString ) );
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
static void meth() throws ClassNotFoundException {
Class classs= Class.forName ( "filename" );
int count = 0;
for (Field field : classs.getDeclaredFields ()){
count++;
}
System.out.println (count );
}
}
If you just add a new .java file to your program, that doesn't add a new class to it. You have to compile it at runtime in order for the Class.forName(...) method to be able to find it.
For a guide on how to do that, see this tutorial.

How to pass a file name as parameter, create and then read the file

I have a method as follows:
public(String input_filename, String output_filename)
{
//some content
}
how to create an input_filename at run time and read the input_filename .I have to pass input_filename as a parameter
Please be patient as I am new to Java
Here a complete sample:
Save it as Sample.java
compile it with: javac Sample.java
run it with: java Sample "in.txt" "out.txt"
or: java Sample
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Sample {
public static void main(String[] args) throws IOException {
if(args.length == 2)
{
doFileStuff(args[0],args[1]);
}
else {
doFileStuff("in.txt","out.txt");
}
}
public static void doFileStuff(String input_filename, String output_filename) throws IOException {
if(!Files.exists(Paths.get(input_filename)))
{
System.err.println("file not exist: " + input_filename);
return;
}
if(!Files.exists(Paths.get(output_filename)))
{
System.err.println("file still exist, do not overwrite it: " + output_filename);
return;
}
String content = new String(Files.readAllBytes(Paths.get(input_filename)));
content += "\nHas added something";
Files.write(Paths.get(output_filename), content.getBytes(StandardCharsets.UTF_8));
}
}
I'm unsure what you want to do with this method, but I hope this can help you a bit.
If you want inputs during runtime, use the Scanner class. A guide on how to use it here
Also if you want an output in your class you should use "return", and not have it as a parameter.
Do note that you haven't named your class yet, or specified the output type.
How it could look:
public String className(String input){
return input;
}

"Attributes and objects cannot be resolved" - error

The following code is for reading or writing files with java, but:
Eclipse prints these errors:
buffer_1 cannot be resolved to a variable
file_reader cannot be resolved
also other attributes...
what is wrong in this code here:
//Class File_RW
package R_2;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.lang.NullPointerException;
public class File_RW {
public File_RW() throws FileNotFoundException, NullPointerException {
File file_to_read = new File("C:/myfiletoread.txt");
FileReader file_reader = new FileReader(file_to_read);
int nr_letters = (int)file_to_read.length()/Character.BYTES;
char buffer_1[] = new char[nr_letters];
}
public void read() {
file_reader.read(buffer_1, 0, nr_letters);
}
public void print() {
System.out.println(buffer_1);
}
public void close() {
file_reader.close();
}
public File get_file_to_read() {
return file_to_read;
}
public int get_nr_letters() {
return nr_letters;
}
public char[] get_buffer_1() {
return buffer_1;
}
//...
}
//main method # class Start:
package R_2;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.lang.NullPointerException;
public class Start {
public static void main(String[] args) {
File_RW file = null;
try {
file = new File_RW();
} catch (NullPointerException e_1) {
System.out.println("File not found.");
}
//...
}
}
I can't find any mistake. I have also tried to include a try catch statement into the constructor of the class "File_RW", but the error messages were the same.
Yes, there are errors in your code - which are of really basic nature: you are declaring variables instead of fields.
Meaning: you have them in the constructor, but they need to go one layer up! When you declare an entity within a constructor or method, then it is a variable that only exists within that constructor/method.
If you want that multiple methods can make use of that entity, it needs to be a field, declared in the scope of the enclosing class, like:
class FileRW {
private File fileToRead = new File...
...
and then you can use your fields within all your methods! Please note: you can do the actual setup within your constructor:
class FileRW {
private File fileToRead;
public FileRW() {
fileToRead = ..
but you don't have to.
Finally: please read about java language conventions. You avoid using "_" within names (just for SOME_CONSTANT)!
javacode already running...thx
same program edited with c++ in visual Studio express...
visit the stackoverflow entry link:
c++ file read write-error: Microsoft Visual C++ Runtime libr..debug Assertion failed, expr. stream.valid()

error: cannot find symbol: class FileNotFoundException

I'm receiving the following error:
printfile.java:6: error: cannot find symbol
throws FileNotFoundException {
^
symbol: class FileNotFoundException
location: class printfile
for the following code:
import java.io.File;
import java.util.Scanner;
public class printfile {
public static void main(String[]args)
throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println (" What file are you looking for? ");
String searchedfile = keyboard.next();
File file = new File(searchedfile);
if (file.exists()) {
System.out.println(" Okay, the file exists... ");
System.out.print(" Do you want to print the contents of " + file + "?");
String response = keyboard.next();
if (response.startsWith("y")) {
Scanner filescan = new Scanner(file);
while (filescan.hasNext()) {
System.out.print(filescan.next());
}
}
else {
System.out.print(" Okay, Have a good day.");
}
}
}
}
How can this error be resolved?
To use a class that is not in the "scope" of your program, (i.e. FileNotFoundException), you have to:
Call it's fully qualified name:
// Note you have to do it for every reference.
public void methodA throws java.io.FileNotFoundException{...}
public void methodB throws java.io.FileNotFoundException{...}
OR
Import the class from it's package:
// After import you no longer have to fully qualify.
import java.io.FileNotFoundException;
...
public void methodA throws FileNotFoundException{...}
public void methodB throws FileNotFoundException{...}
Suggest also taking a look in this question, explains pretty much everything you might want to know about Java's acess control modifiers.

Problems printing a directory listing to the console

Sorry about readability. Stack appears to be trimming spaces from code lines & indents don't show up. Hrmph.
This was printing to the console without any problems...
CGT\whgdata\whnvp33.txt << EXPECTED OUTPUT (excerpt)
CGT\whgdata\whnvt30.txt
CGT\whgdata\whnvt31.txt
CGT\whgdata\whnvt32.txt
CGT\whgdata\whnvt33.txt
CGT\whgdef.txt
CGT\whgdhtml.txt
CGT\whibody.txt
etc....
...until I tried printing the hashtable to a file. Since that point, getFileListing isn't recognized as a valid symbol.
FileListing2.java:17: error: cannot find symbol
List<File> files = FileListing2.getFileListing(startingDirectory);
symbol: method getFileListing(File)
location: class FileListing2
1 error
Can someone lend a second set of eyes to help me uncover what I accidentally/overwrote. I'm sure it's something obvious. :\
import java.util.*;
import java.io.*;
import java.nio.*;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption.*;
import java.nio.file.Paths;
//
public final class FileListing2 {
public static void main(String... aArgs) {
//
File startingDirectory= new File("CGT");
File outputFile = new File("CGTOutput.txt");
List<File> files = FileListing2.getFileListing(startingDirectory);
OutputStream output = null;
//
for(File file : files ) {
System.out.println(file); //print filenames
}
}
}
If your code is all you have for FileListing2, than there is no getFileListing() method for LileListing2, only a main() method
Yeah it IS something very obious, your class FileListing2 does not contain a method getFileListing(File). And it has to be static, the way you're trying to call it:
public final class FileListing2 {
public static void main(String... aArgs) {
//
File startingDirectory= new File("CGT");
File outputFile = new File("CGTOutput.txt");
List<File> files = FileListing2.getFileListing(startingDirectory);
OutputStream output = null;
//
for(File file : files ) {
System.out.println(file); //print filenames
}
}
public static List<File> getFileListing(File f) {
/* implementation */
}
}

Categories

Resources