Program never finds Scanner - java

I have two classes that read in a file, Project2 and CMSReader. However, in the setColumnsInFile method in the CMSReader class never finds the scanner symbol. Appreciate the help.
Here is the Project2 class.
import java.util.*;
import java.io.FileNotFoundException;
import java.io.File;
public class Project2
{
public static void main(String[] args)
{
boolean found = false;
Scanner sc = null;
String fileName = null;
try
{
fileName = args[0];
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.print("File not found! Please try again.");
System.exit(0);
}
File f = null;
try
{
f = new File(fileName);
sc = new Scanner(f);
found = true;
}
catch(FileNotFoundException e)
{
System.out.print("File not found!");
}
CMSReader inputFile = new CMSReader();
inputFile.readFile(args);
System.out.println("hello");
inputFile.setColumnsInFile(args);
System.out.println("bye");
}
}
Here is the CMSReader Class:
import java.util.*;
import java.io.*;
public class CMSReader
{
public Scanner readFile(String[] file)
{
String filename = file[0];
Scanner sc = null;
File f = null;
try
{
f = new File(filename);
sc = new Scanner(f);
}
catch(IOException e)
{
}
return sc;
}
public CMSReader()
{
}
public String setColumnsInFile(String[] file)
{
Scanner sc = null;
String numberOfVariables = null;
try
{
sc = readFile(file);
boolean flag = true;
while(sc.hasNextline() && flag == true)
{
if(sc.nextline().equals("Columns in File: "))
{
flag = false;
String splitVariables = sc.nextline();
String[] numberOfVariablesParts = splitVariables.split(": ");
numberOfVariables = numberOfVariablesParts[1];
}
}
}
catch(IOException e)
{
}
return numberOfVariables;
}
}

You have sc.Nextline in one place and sc.nextline in another.
I would recommend using an IDE like Eclipse or Intellij to help you with code completion and programming misspellings.

You have typos in your second class:
Change sc.hasNextline() to sc.hasNextLine() and sc.nextline() to sc.nextLine()
Also remove the try & catch of IOException since it will never be thrown.

Related

how to use relative file path to read a file in java?

file path is not working, input1.txt is located in the same directory as library.java.
What should i do to correct it ?
How should i give path so that it read thr text file ?
package SimpleLibrarySystem;
import java.time.LocalDateTime;
import java.util.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
public class Library
{
ArrayList <Book> var = new ArrayList<Book>();
HashMap<Book, LocalDateTime> var1 = new HashMap<Book, LocalDateTime>();
public Library(String person, LocalDateTime time)
{
try{
File myfile = new File("input1.txt") ;
Scanner br = new Scanner(myfile);
String line = br.nextLine();
while ((line != null))
{
String a = line;
line = br.nextLine();
String b = line;
Book a1 = new Book(a,b,person);
Book a2 = new Book (a,b, "");
var.add(a2);
var1.put(a1,time);
//System.out.println(a + " "+ b);
line = br.nextLine();
}
br.close();
}
catch (Exception e)
{
System.out.println("not working");
}
}
}
with code:
public class Main{
public static void main(String[] args) {
int counter = 0;
try (FileReader fileReader = new FileReader("src/file.txt"); Scanner sc = new Scanner(fileReader)) {
while (sc.hasNextLine()) {
++counter;
sc.nextLine();
}
} catch (Exception e) {
throw new IllegalStateException(e.getMessage());
}
System.out.println(counter);
}
}
checkout: how to read file in Java

Java Eclipse Visitor Not Leaving Main() of test file

I'm attempting collect all the methods in a Java file using the Eclipse AST package. I believe that I have the CompilationUnit created successfully. However when I attempt to use a visitor to collect the information it doesn't go past the main() method of the file I'm testing.
public void parseCode(String fileName) {
String strSource = "";
try {
strSource = codeToString(fileName);
} catch (Exception e) {
e.printStackTrace();
}
ASTParser parser = ASTParser.newParser(AST.JLS8);
parser.setSource(strSource.toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
final CompilationUnit cu = (CompilationUnit) parser.createAST(new NullProgressMonitor());
SCTVisitor v = new SCTVisitor();
cu.accept(v);
System.out.println(v.m);
}
public class SCTVisitor extends ASTVisitor{
List<SimpleName> m = new ArrayList<SimpleName>();
SCTVisitor(){
System.out.println("What is love");
}
#Override public boolean visit(MethodInvocation node) {
this.m.add(node.getName());
return true;
}
}
This is part of the file I'm using to test:
import java.util.Map;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.UIManager;
public class WordCount {
public static void main(String[] args) {
System.out.println("Cheese");
countWordsViaGUI();
}
// allow user to pick file to exam via GUI.
// allow multiple picks
public static void countWordsViaGUI() {
setLookAndFeel();
try {
Scanner key = new Scanner(System.in);
do {
System.out.println("Opening GUI to choose file.");
Scanner fileScanner = new Scanner(getFile());
Stopwatch st = new Stopwatch();
st.start();
ArrayList<String> words = countWordsWithArrayList(fileScanner);
st.stop();
System.out.println("time to count: " + st);
System.out.print("Enter number of words to display: ");
int numWordsToShow = Integer.parseInt(key.nextLine());
showWords(words, numWordsToShow);
fileScanner.close();
System.out.print("Perform another count? ");
} while(key.nextLine().toLowerCase().charAt(0) == 'y');
key.close();
}
catch(FileNotFoundException e) {
System.out.println("Problem reading the data file. Exiting the program." + e);
}
}
My results are:
[println, countWordsViaGUI]
My expected results are:
[println, countWordsViaGUI, setLookAndFeel, scanner, println, getFile, Scanner, ...]
Please let me know if you have any insight into this problem.

JAVA Scanner object inside my constructor, cannot call it in my method

I am required to pass a file object to my constructor, and I am required to make a constructor in my method.
I am very confused as to why my code does not compile. It gives me several errors, and i am still struggling with the first one: sc cannot be resolved.
This is my class:
public class Reverser {
public Reverser(File file) throws FileNotFoundException, IOException {
Scanner sc = new Scanner(file);
}
public void reverseLines(File outpr) {
PrintWriter pw = new PrintWriter(outpr);
while (sc.hasNextLine()) {
String sentence = sc.nextLine();
String[] words = sentence.split(" ");
new ArrayList < String > (Arrays.asList(words));
Collections.reverse(wordsarraylist);
if (wordsarraylist != null) {
String listString = wordsarraylist.toString;
listString = listString.subString(1, listString.length() - 1);
}
}
pw.write(listString);
}
}
and this is my main:
import java.util.*;
import java.io.*;
public class ReverserMain {
public static void main(String[] args) throws FileNotFoundException, IOException {
Reverser r = new Reverser(new File("test.txt"));
}
}
Are you adding more functions to this class? You can keep it simple with an approach like this:
public static void reverseLines(File inputFile, File outPutFile) {
try (Scanner sc = new Scanner(inputFile); PrintWriter pw = new PrintWriter(outPutFile)) {
while (sc.hasNextLine()) {
// your logic goes in here
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
You can use try-catch block with resources, will auto close the streams.
And when you are writing to the output file,if the file is already existing, do you want to append data or erase the contents of the file and write to a completely new file??
if you must use constructors:
public class Reverser {
File inputFile;
File outputFile;
public Reverser(File inputFile, File outputFile) {
this.inputFile = inputFile;
this.outputFile = outputFile;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public void reverseLines() {
try (Scanner sc = new Scanner(inputFile); PrintWriter pw = new PrintWriter(outputFile)) {
while (sc.hasNextLine()) {
// your logic goes in here
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Declare sc outside of the constructor :
Scanner sc = null ;
public Reverser(File file)throws FileNotFoundException, IOException{
sc = new Scanner (file);
}

How to check if file content is empty

I am trying to check if a file content is empty or not. I have a source file where the content is empty.
I tried different alternatives.But nothing is working for me.
Here is my code:
Path in = new Path(source);
/*
* Check if source is empty
*/
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(fs.open(in)));
} catch (IOException e) {
e.printStackTrace();
}
try {
if (br.readLine().length() == 0) {
/*
* Empty file
*/
System.out.println("In empty");
System.exit(0);
}
else{
System.out.println("not empty");
}
} catch (IOException e) {
e.printStackTrace();
}
I have tried using -
1. br.readLine().length() == 0
2. br.readLine() == null
3. br.readLine().isEmpty()
All of the above is giving as not empty.And I need to use -
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(fs.open(in)));
} catch (IOException e) {
e.printStackTrace();
}
Instead of new File() etc.
Please advice if I went wrong somewhere.
EDIT
Making little more clear. If I have a file with just whitespaces or
without white space,I am expecting my result as empty.
You could call File.length() (which Returns the length of the file denoted by this abstract pathname) and check that it isn't 0. Something like
File f = new File(source);
if (f.isFile()) {
long size = f.length();
if (size != 0) {
}
}
To ignore white-space (as also being empty)
You could use Files.readAllLines(Path) and something like
static boolean isEmptyFile(String source) {
try {
for (String line : Files.readAllLines(Paths.get(source))) {
if (line != null && !line.trim().isEmpty()) {
return false;
}
}
} catch (IOException e) {
e.printStackTrace();
}
// Default to true.
return true;
}
InputStream is = new FileInputStream("myfile.txt");
if (is.read() == -1) {
// The file is empty!
} else {
// The file is NOT empty!
}
Of course you will need to close the is and catch IOException
You can try something like this:
A Utility class to handle the isEmptyFile check
package com.stackoverflow.answers.mapreduce;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class HDFSOperations {
private HDFSOperations() {}
public static boolean isEmptyFile(Configuration configuration, Path filePath)
throws IOException {
FileSystem fileSystem = FileSystem.get(configuration);
if (hasNoLength(fileSystem, filePath))
return false;
return isEmptyFile(fileSystem, filePath);
}
public static boolean isEmptyFile(FileSystem fileSystem, Path filePath)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(fileSystem.open(filePath)));
String line = bufferedReader.readLine();
while (line != null) {
if (isNotWhitespace(line))
return false;
line = bufferedReader.readLine();
}
return true;
}
public static boolean hasNoLength(FileSystem fileSystem, Path filePath)
throws IOException {
return fileSystem.getFileStatus(filePath).getLen() == 0;
}
public static boolean isWhitespace(String str) {
if (str == null) {
return false;
}
int length = str.length();
for (int i = 0; i < length; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
public static boolean isNotWhitespace(String str) {
return !isWhitespace(str);
}
}
Class to test the Utility
package com.stackoverflow.answers.mapreduce;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
public class HDFSOperationsTest {
public static void main(String[] args) {
String fileName = "D:/tmp/source/expected.txt";
try {
Configuration configuration = new Configuration();
Path filePath = new Path(fileName);
System.out.println("isEmptyFile: "
+ HDFSOperations.isEmptyFile(configuration, filePath));
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}

Java I/O writing, mixingcase and getExtension problems

I am changing names of all files in directory and if it's text file I am changing the content but it doesn't seem to work the name of the file is changed right but content is blank/gone heres is my code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.commons.io.FilenameUtils;
public class FileOps {
public static File folder = new File(
"C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files");
public static File[] listOfFiles = folder.listFiles();
public static void main(String[] argv) throws IOException {
toUpperCase();
}
public static void toUpperCase() throws FileNotFoundException {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
String newname = mixCase(listOfFiles[i].getName());
if (listOfFiles[i].renameTo(new File(folder, newname))) {
String extension = FilenameUtils
.getExtension(listOfFiles[i].getName());
if (extension.equals("txt") || extension.equals("pdf")
|| extension.equals("docx")
|| extension.equals("log")) {
rewrite(listOfFiles[i]);
System.out.println("Done");
}
}
} else {
System.out.println("Nope");
}
}
}
public static String mixCase(String in) {
StringBuilder sb = new StringBuilder();
if (in != null) {
char[] arr = in.toCharArray();
if (arr.length > 0) {
char f = arr[0];
boolean first = Character.isUpperCase(f);
for (int i = 0; i < arr.length; i++) {
sb.append((first) ? Character.toLowerCase(arr[i])
: Character.toUpperCase(arr[i]));
first = !first;
}
}
}
return sb.toString();
}
public static void rewrite(File file) throws FileNotFoundException {
FileReader reader = new FileReader(file.getAbsolutePath());
BufferedReader inFile = new BufferedReader(reader);
try {
FileWriter fwriter = new FileWriter(file.getAbsolutePath());
BufferedWriter outw = new BufferedWriter(fwriter);
while (inFile.readLine() != null) {
String line = mixCase(inFile.readLine());
outw.write(line);
}
inFile.close();
outw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
There is several issue with your code:
Your rewrite function is perform on old name File. It should be done on the renamed File:
String newname = mixCase(listOfFiles[i].getName());
File renamedFile = new File(folder, newname);
if (listOfFiles[i].renameTo(renamedFile )) {
String extension = FilenameUtils
.getExtension(listOfFiles[i].getName());
if (extension.equals("txt") || extension.equals("pdf")
|| extension.equals("docx")
|| extension.equals("log")) {
rewrite(renamedFile);
System.out.println("Done");
}
}
you are trying to read docx and pdf file like regular text file. This cannot work. You will have to use external library like POI and pdf Box
Your rewrite function is not safe. You must unsure to close the ressources:
FileReader reader = null;
BufferedReader inFile = null;
try {
reader = new FileReader(file.getAbsolutePath());
inFile = new BufferedReader(reader);
FileWriter fwriter = new FileWriter(file.getAbsolutePath());
BufferedWriter outw = new BufferedWriter(fwriter);
while (inFile.readLine() != null) {
String line = mixCase(inFile.readLine());
outw.write(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally
{
if(infile != null)
inFile.close();
if(reader != null)
reader .close();
}
You can't re-write a file on top of itself. you need to write the new content to a new file, then rename again.

Categories