Cannot read file using Scanner, never gets into loop - java

I am trying to read a text file in order to copy some parts of it into a new text file.
This is how I create my Scanner item :
// folder
File vMainFolder = new File(System.getProperty("user.home"),"LightDic");
if (!vMainFolder.exists() & !vMainFolder.mkdirs()) {
System.out.println("Missing LightDic folder.");
return;
}
// file
System.out.println("Enter the source file's name : ");
Scanner vSc = new Scanner(System.in);
String vNomSource = vSc.next();
Scanner vSource;
try {
vSource = new Scanner(new File(vMainFolder, vNomSource+".txt"));
} catch (final java.io.FileNotFoundException pExp) {
System.out.println("Dictionnary not found.");
return;
}
And this is how I wrote my while structure :
while (vSource.hasNextLine()) {
System.out.println("test : entering the loop");
String vMot = vSource.nextLine(); /* edit : I added this statement, which I've forgotten in my previous post */
}
When executing the program, it never prints "test : entering the loop".
Of course, this file I am testing is not empty, it is a list of words like so :
a
à
abaissa
abaissable
abaissables
abaissai
I don't understand what I did wrong, I've used this method a few times in the past.

Problem solved.
I don't really know why, but I solved the problem changing the encoding of my FRdic.txt file from ANSI to UTF-8, and then the file was read.
Thanks to everyone who tried to help me.
Is it normal that a text file encoded in ANSI is not read by the JVM ?

Related

Printing a Specified File Exercise Java

Taking a beginners course in Java and I am stuck on one of the exercises. We're meant to print the text within a specific file, which we can find via the file's name which was inputted by a user. In our previous exercise, we learned that
try(Scanner scanner = new Scanner(Paths.get("data.txt")))
would find the text within the file "data.txt", but I am unsure about how to convert this into finding any file name inputted by the user.
More details below.
Exercise: Write a program that asks the user for a string, and then prints the contents of a file with a name matching the string provided. You may assume that the user provides a file name that the program can find.
The exercise template contains the files "data.txt" and "song.txt", which you may use when testing the functionality of your program. The output of the program can be seen below for when a user has entered the string "song.txt". The content that is printed comes from the file "song.txt". Naturally, the program should also work with other filenames, assuming the file can be found.
My code so far is:
import java.nio.file.Paths;
import java.util.Scanner;
public class PrintingASpecifiedFile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Which file should have its contents printed?");
String fileName = scanner.nextLine();
//try(Scanner scanner = new Scanner(Paths.get(fileName))) {
try(scanner = Paths.get(fileName)) { // this part of the code is underlined red
while (scanner.hasNextLine()){
String output = scanner.nextLine();
System.out.println(output);
}
}
catch (Exception e){
System.out.println("Error: " + e.getMessage());
}
}
}
I have tried searching how to add a new scanner as that was a suggestion but every time I've tried it gets an error. Also the "try" section is underlined red and cannot seem to figure out why. The underlined red part says variables in try-with-resources are not supported in -source 8
If anyone has tips, I would really appreciate it! Thank you!
You used one Scanner for reading the file path from the console.
You need an other Scanner (or reader alternative) for reading the file.
try (Scanner fileScanner = new Scanner(fileName)) {
try (Scanner fileScanner = new Scanner(Paths.get(fileName))) {

How do i create/modify the contents of a file before i create it in a Java program i have made?

Hey here is my code i have created its a simple file creation program as i have only been using java for the past 2 days. I'm only 13 so please be simple :)
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Filecreator
{
public static void main( String[] args )
{
Scanner read = new Scanner (System.in);
String y;
String u;
try {
System.out.println("Please enter the name of your file!");
y = read.next();
while (y.contains(".") || y.contains(",") || y.contains("{") || y.contains("}") || y.contains("#")){
System.out.println("Your Filename contains an incorrect character you may only use Number 0-9 And Letters A-Z");
System.out.println("Please Re-enter your file name");
y = read.next();
}
System.out.println("Please enter the file type name");
u = read.next();
while (u.contains(".") || u.contains(",") || u.contains("{") || u.contains("}") || u.contains("#") ){
System.out.println("Your File-type name contains an incorrect character you may only use Number 0-9 And Letters A-Z");
System.out.println("Please Re-enter your file-type name");
u = read.next();
}
File file = new File( y + "." + u );
if (file.createNewFile()){
System.out.println("File is created!");
System.out.println("The name of the file you have created is called " + y + file);
}else{
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you run it on a program such as Eclipse you will see the output. But i want to be able to edit the [file's] contents before i finally choose the name and the file type and then save it. Is there anyway i can do this? Thanks - George
Currently you are printing everything out to the console - this is done when you use System.out.println(...).
What you can do is to write the output somewhere else. How you can do this ? The easiest way how to do this is to Use StringBuilder:
http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
This is a code sample :
StringBuilder sb = new StringBuilder();
sb.append("one ");
sb.append("two");
String output = sb.toString(); // output contains string "one two"
Now you have your whole output in one string. If you look at StringBuilder documentation (link is above) you can see that there are other useful methods like insert or delete that help you to modify your output before you convert it to string (with toString method). Once all your modifications are done you can write this string to a file.
For writing a String to a file this could be helpful :
How do I save a String to a text file using Java?
This is good enough approach if you are writing small files (up to few MB). If you want to write bigger files you shouldn't store the whole string in memory before you write it to a file. In such scenarios you should create smaller strings and write them to a file. There is a good tutorial for that :
http://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/
Read lines until the line contains a special end-of-file marker. Eg, the old unix program 'mail' append all lines until a line consisting of a single '.' is read.
// insert this before reading the filename
StringBuilder content = new StringBuilder();
s = read.next();
while( !s.equals(".")) {
content.append(s);
content.append(String.format("%n"));
s = read.next();
}
The look at this: write a string into file (better answer than the other) and use that as an example of how to actually write the contents to the file, after it has been created.
p.s.
Pro-tip: I'm sure you have noticed that you have duplicated exactly the same line for checking if a filename is valid. A good programmer would notice this too and "extract" a method that does the logic in one place.
Example:
boolean isValidFilename( String s ) {
return !(y.contains(".") || y.contains(",") || y.contains("{") || y.contains("}") || y.contains("#")));
}
You may then replace the checks;
while (!isValidFilename( u )){
System.out.println("Your File-type name contains an incorrect character...etc");
}
This is good since you don't have to repeat tricky code, which means there are fewer places to do errors in. Btw, the negations (!) are there to avoid negative names (invalid=true) because you might end up with a double negation when using them (not invalid=true) and that may be a bit confusing.
You can't edit a file before you create it. You can make changes to the data you are going to write to the file once you crate it; since you control both that data and the creation of the file, there should be no problem.

How to append existing line in text file

How do i append an existing line in a text file? What if the line to be edited is in the middle of the file? Please kindly offer a suggestion, given the following code.
Have went through & tried the following:
How to add a new line of text to an existing file in Java?
How to append existing line within a java text file
My code:
filePath = new File("").getAbsolutePath();
BufferedReader reader = new BufferedReader(new FileReader(filePath + "/src/DBTextFiles/Customer.txt"));
try
{
String line = null;
while ((line = reader.readLine()) != null)
{
if (!(line.startsWith("*")))
{
//System.out.println(line);
//check if target customer exists, via 2 fields - customer name, contact number
if ((line.equals(customername)) && (reader.readLine().equals(String.valueOf(customermobilenumber))))
{
System.out.println ("\nWelcome (Existing User) " + line + "!");
//w target customer, alter total number of bookings # 5th line of 'Customer.txt', by reading lines sequentially
reader.readLine();
reader.readLine();
int total_no_of_bookings = Integer.valueOf(reader.readLine());
System.out.println (total_no_of_bookings);
reader.close();
valid = true;
//append total number of bookings (5th line) of target customer # 'Customer.txt'
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(filePath + "/src/DBTextFiles/Customer.txt")));
writer.write(total_no_of_bookings + 1);
//writer.write("\n");
writer.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
//finally
// {
//writer.close();
//}
}
}
}
To be able to append content to an existing file you need to open it in append mode. For example using FileWriter(String fileName, boolean append) and passing true as second parameter.
If the line is in the middle then you need to read the entire file into memory and then write it back when all editing was done.
This might be workable for small files but if your files are too big, then I would suggest to write the actual content and the edited content into a temp file, when done delete the old one an rename the temp file to be the same name as the old one.
The reader.readLine() method increments a line each time it is called. I am not sure if this is intended in your program, but you may want to store the reader.readline() as a String so it is only called once.
To append a line in the middle of the text file I believe you will have to re-write the text file up to the point at which you wish to append the line, then proceed to write the rest of the file. This could possibly be achieved by storing the whole file in a String array, then writing up to a certain point.
Example of writing:
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path)));
writer.write(someStuff);
writer.write("\n");
writer.close();
You should probably be following the advice in the answer to the second link you posted. You can access the middle of a file using a random access file, but if you start appending at an arbitrary position in the middle of a file without recording what's there when you start writing, you'll be overwriting its current contents, as noted in this answer. Your best bet, unless the files in question are intractably large, is to assemble a new file using the existing file and your new data, as others have previously suggested.
AFAIK you cannot do that. I mean, appending a line is possible but not inserting in the middle. That has nothing to do with java or another language...a file is a sequence of written bytes...if you insert something in an arbitrary point that sequence is no longer valid and needs to be re-written.
So basically you have to create a function to do that read-insert-slice-rewrite

Read the five score in a textfile then print them back with the new score added to the list - ANDROID

In my program when the player submits a score it gets added to a local text file called localHighScores. This is list of the top five score the player has achieved while on that specific device.
I wasn't sure how to write to a new line using FileOutputStream (if you know please share), so instead I've inputted a space in between each score. Therefore what I am trying to do is when the player clicks submit the program will open the file and read any current data is saved. It will save it to an String Array, each element being one of the five score in the text file and when it hits a 'space' in the fie it will add the score just read to the write array element
The code I currently have is as follows:
String space = " ";
String currentScoreSaved;
String[] score = new String[5];
int i = 0;
try
{
BufferedReader inputReader = new BufferedReader(new InputStreamReader(openFileInput("localHighScore.txt")));
String inputString;StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null && i < 6)
{
if((inputString = inputReader.readLine()) != space)
{
stringBuffer.append(inputString + "\n");
i++;
score[i] = stringBuffer.toString();
}
}
currentScoreSaved = stringBuffer.toString();
FileOutputStream fos = openFileOutput("localHighScore.txt", Context.MODE_PRIVATE);
while (i < 6)
{
i++;
fos.write(score[i].getBytes());
fos.write(space.getBytes());
}
fos.write(localHighScore.getBytes());
//fos.newLine(); //I thought this was how you did a new line but sadly I was mistaken
fos.close();
}
catch(Exception e)
{
e.printStackTrace();
}
Now you will notice this doesn't re arrange the score if a new highscore is achieved. That I am planning on doing next. For the moment I am just trying to get the program to do the main thing which is read in the current data, stick it in an Array then print it back to that file along with the new score
Any Ideas how this might work, as currently it's printing out nothing even when I had score in the textfile before hand
I'm only a first year student in Java programming and I am a new user here at stackoverflow.com, so pardon me if coding for android has some special rules I don't know about, which prevents this simple and humble example from working. But here is how I would read from a file in the simplest of ways.
File tempFile = new File("<SubdirectoryIfAny/name_of_file.txt");
Scanner readFile = new Scanner( tempFile );
// Assuming that you can structure the file as you please with fx each bit of info
// on a new line.
int counter = 0;
while ( readFile.hasNextLine() ) {
score[counter] = readFile.nextLine();
counter++;
}
As for the writing back to the file? Put it in an entirely different method and simply make a simplified toString-like method, that prints out all the values the exact way you want them in the file, then create a "loadToFile" like method and use the to string method to print back into the file with a printstream, something like below.
File tempFile = new File("<SubdirectoryIfAny/name_of_file.txt");
PrintStream write = new PrintStream(tempFile);
// specify code for your particular program so that the toString method gets the
// info from the string array or something like that.
write.print( <objectName/this>.toStringLikeMethod() );
// remember the /n /n in the toStringLikeMethod so it prints properly in the file.
Again if this is something you already know, which is just not possible in this context please ignore me, but if not I hope it was useful. As for the exceptions, you can figure that you yourself. ;)
Since you are a beginner, and I assume you are trying to get things off the ground as quickly as possible, I'd recommend using SharedPreferences. Basically it is just a huge persistent map for you to use! Having said that... you should really learn about all the ways of storage in Android, so check out this document:
http://developer.android.com/guide/topics/data/data-storage.html
The Android docs are awesome! FYI SharedPreferences may not be the best and awesomest way to do this... but I'm all for quick prototyping as a learner. If you want, write a wrapper class around SharedPreferences.

Java - Load file, replace string, save

I have a program that loads lines from a user file, then selects the last part of the String (which would be an int)
Here's the style it's saved in:
nameOfValue = 0
nameOfValue2 = 0
and so on. I have selected the value for sure - I debugged it by printing. I just can't seem to save it back in.
if(nameOfValue.equals(type)) {
System.out.println(nameOfValue+" equals "+type);
value.replace(value, Integer.toString(Integer.parseInt(value)+1));
}
How would I resave it? I've tried bufferedwriter but it just erases everything in the file.
My suggestion is, save all the contents of the original file (either in memory or in a temporary file; I'll do it in memory) and then write it again, including the modifications. I believe this would work:
public static void replaceSelected(File file, String type) throws IOException {
// we need to store all the lines
List<String> lines = new ArrayList<String>();
// first, read the file and store the changes
BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
while (line != null) {
if (line.startsWith(type)) {
String sValue = line.substring(line.indexOf('=')+1).trim();
int nValue = Integer.parseInt(sValue);
line = type + " = " + (nValue+1);
}
lines.add(line);
line = in.readLine();
}
in.close();
// now, write the file again with the changes
PrintWriter out = new PrintWriter(file);
for (String l : lines)
out.println(l);
out.close();
}
And you'd call the method like this, providing the File you want to modify and the name of the value you want to select:
replaceSelected(new File("test.txt"), "nameOfValue2");
I think most convenient way is:
Read text file line by line using BufferedReader
For each line find the int part using regular expression and replace
it with your new value.
Create a new file with the newly created text lines.
Delete source file and rename your new created file.
Please let me know if you need the Java program implemented above algorithm.
Hard to answer without the complete code...
Is value a string ? If so the replace will create a new string but you are not saving this string anywhere. Remember Strings in Java are immutable.
You say you use a BufferedWriter, did you flush and close it ? This is often a cause of values mysteriously disappearing when they should be there. This exactly why Java has a finally keyword.
Also difficult to answer without more details on your problem, what exactly are you trying to acheive ? There may be simpler ways to do this that are already there.

Categories