Java scanner not recognizing filename? - java

I am writing a parser that removes all punctuation from a text file and puts the words in a Map that associates each word with the number of times it occurs in the file. I use a Scanner to read the txt file, but it reads the file name instead of the actual file. For instance:
parse("./src/filename.txt")
is read as "srcfilenametxt" and is associated with a value 1. Unfortunately, I can't include more code because this is for a class assignment. How do I get it to correctly read the file?

If Scanner is constructed with a string parameter it scans the string, not the file named by the string. You'd need a line like:
Scanner in = new Scanner(new File("./src/filename.txt"));

Use bufferedreader to read a file
BufferedReader br = new BufferedReader(new FileReader("filename.txt"));

Related

Java Scanner can't read from only File Name

I'm making a Java program to read some scores from a .csv file and calculate the average of those scores. To read from the file, I'm using the Scanner Class.
First, I create a scanner to read from my file:
Scanner scanner = new Scanner(new File("TempFile.csv"));
I expected this to work, but it returns a FileNotFoundException. So, I replaced TempFile.csv with the file's absolute file name.
Scanner scanner = new Scanner(new File(C:\\Users\....));
This gave me the result I wanted, and I was able to parse the file. I'm new to Java, but I know that it's bad practice to use the absolute file name.
How can I use only the short file name?
Scanner scanner = new Scanner(new File (new File("TempFile.csv").getAbsolutePath()));
Use above.
"TempFile.csv" is a relative path. It's relative to the working directory of your java program. This directory is the value of the System property "user.dir". The following line of code gives you that value...
String workingDirectory = System.getProperty("user.dir");
Hence if you are getting FileNotFoundException, it probably means file "TempFile.csv" is not located in the working directory of your java program.
By the way, since java 8, class java.nio.file.Files contains method readAllLines. So if file "TempFile.csv" is not too big, readAllLines may be a simpler alternative to class Scanner. Note though that you still need to provide the correct path to the file when calling that method.

How to replace a line in a text file using Java?

I have a text file with various key value pairs separated with a '--'.
Below is the code I have so far
File file = new File("C:\\StateTestFile.txt");
BufferedWriter out = new BufferedWriter(file.getAbsolutePath());
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
if(line.contains("content_style")) {
//Write to the line currently reading and save back to the file
}
}
br.close();
out.close();
What I would like to do is read this text file and replace the value of a specific line with something I specify. So id want to find the 'content_style' line and replace 'posh' with 'dirty'.
How can I do this?
simply use:
line = line.replaceAll("posh", "dirty"); // as strings are immutable in java
This can be done in-place on a single file only if you are sure that the string you are replacing is exactly the same length in bytes as the string that replaces it. Otherwise, you can't add or delete characters in a single file, but you can create a new file.
Open the source file for reading.
Open the destination file for writing.
Read each line in the source file, use replaceAll, and write it to the destination file.
Close both files.
Alternate method that preserves the key-value semantics:
Open the source file for reading.
Open the destination file for writing.
Split each line in the source file into a key and value pair. If the key equals "content_style", write the key and "dirty" to the destination file. Otherwise write the key and value.
Close both files.
Finally, delete the old file and rename the new file on top of the old one. If you're going to be doing key-value manipulations often, and you don't want to write out a new file all the time, it might be worth it to use a database. Look for a JDBC driver for SQLite.

Do something upon file exist

so i created a java program that outputs to a file (classname.java) the basic template of a java program...
/*
Nathaly Morcillo
Nov 19 2013
Header comments
*/
public class test{
public static void main String([] args){
}
}
However what i don't understand is:
After collecting the required input, check to see if the requested file (classname.java) already exists. If it does not, the program proceeds as described above. If it does exist, the program simply adds the header comments (because you probably didn’t put them in before anyhow). Hint: since you have to read from then write to the same file, try using
Scanner scan = new Scanner(file);
scan.useDelimiter("\\Z");
String content = scan.next();
method to read in and store the contents of the whole file before writing out the file plus the new header comments.
I don't understand what to do with the scan.useDelimiter("\\Z");
What I have is:
File outputFile = new File(outputFileName);
if (outputFile.exists()) {
} else {
pout.println(
System.out.println("Contents of file");
pout.close();
}
Since this looks like homework, I'm not going to give you the answer, but I'll try to explain what's going on and give you some hints.
Scanner scan = new Scanner(file);
This creates a new Scanner object, which will allow you to read from the given file.
scan.useDelimiter("\\Z");
A Scanner object splits its input into what are called tokens. It does this by using a delimeter. Basically, it looks for anything that matches its delimeter and cuts its input at every matching point. In your case, "\\Z" is a regular expression which matches only the end of input. That causes your Scanner to read in the entire file.
String content = scan.next();
This returns the next token in your Scanner's input. Since you set the delimeter to "\\Z", this is the entire file.
Now onto the actual program. Obviously, you can't read in from a file that doesn't exist, so you'd probably only want to use your Scanner if outputFile.exists() returns true.

Overwriting data in a file starting from a given line in java

I want to specifically overwrite data in a file starting from a given line.
Suppose that I find out that I have to write some data in the file from line x ( I have already found x) . How would I overwrite everything after there.
Also is there a function that would directly take my line and string and overwrite the file.
An alternate approach would be, read the file line by line by scanner class (as described below), store those lines into any variable, say, arraylist, then appennd your new string once you have read the lines and write the whole list into a new file.
Example:
File file = new File("file.txt");
Scanner scanner = new Scanner(file).useDelimiter("\n");
String line = scanner.next();
//Store in the list
//Append the new lines
//Write the whole list into a new file

How to Read 1st line of a file with BufferedReader?

I was experimenting with BufferedReader to read 1st line file to a string. How do I do this? Also how can I read an entire file to a string? How to read a particular line like readline(int line) without iterating through the previous lines?
File namefile = new File(root, ".name");
FileReader namereader = new FileReader(namefile);
BufferedReader in = new BufferedReader(namereader);
You can use BufferedReader.readLine() to get the first line.
Note that the next call to readLine() will get you the 2nd line, and the next the 3rd line....
EDIT:
If you want to specify a specific line, as your comment suggest - you might want to use Apache Commons FileUtils, and use: FileUtils.readLines(). It will get you a List<String> which you can handle like any list, including getting a specific line. Note that it has more overhead because it reads the entire file, and populates a List<String> with its lines.
Um, what's wrong with BufferedReader.readLine()?
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
(I don't see any sign of a readFile() method though - what documentation were you looking at?)
Personally I prefer to use FileInputStream wrapped in InputStreamReader instead of FileReader by the way, as otherwise it will always use the platform default encoding - are you sure what's what you want?
final File namefile = new File(root, ".name");
final FileReader namereader = new FileReader(namefile);
final BufferedReader in = new BufferedReader(namereader);
in.readLine();
If you use the BufferedReader to read the File there should be a Method called
readLine()
wich reads exactly one Line.
http://developer.android.com/reference/java/io/BufferedReader.html
See the readline() method of the BufferedReader.
http://docs.oracle.com/javase/1.4.2/docs/api/java/io/BufferedReader.html#readLine%28%29

Categories