Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: Trouble Reading Line in File

  1. #1
    Junior Member
    Join Date
    Mar 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Trouble Reading Line in File

    [SOLVED]

    Program description: This part of the program is supposed to go through all the files in the directory, add all values in the file from the second line onwards, then recreate the text file with the sum of the previous values as the only value in the file (after the first line, which is the header).

    The problem: All seems to go well until halfway through the "findTotal" method's processing. Using dummy print statements, I can see where the variable "val" (defined as everything on the current line past the first character equals 0; when the actual value in the text file is a non-zero number (64 is the value I've been using). I can quite clearly see that the value it should be picking up is not zero by simply opening the text files that are being read.

    I have spent several hours trying to figure out a solution and am totally lost as to what the problem could be. This process should work, I have an alternate version of the program where a single selected file is used instead of the entire directory, which runs perfectly. I can't tell where the difference is that could be causing this issue.

    There's a significant amount of code involved, but I'll try to cut away what I can to make it easier to understand.

    String[] files = dir.list();
     
    System.out.println("Please enter the amount to decay the target files");
    decayVal = Double.parseDouble(input.readLine());
     
    for(int i = 0; i < files.length; i++){
    	findTotal(files[i]);
            BufferedReader fileData = new BufferedReader(new FileReader(files[i]));
     
    	fileData.readLine();
    	String totalString = fileData.readLine();
    	total = Integer.parseInt(totalString.substring(1));
    	System.out.println("Total equals " + total);
    	fileData.close();
     
    	total -= (total * (decayVal / 100));
     
    	File targetFile = new File(files[i]);
    	targetFile.delete();
    	targetFile.createNewFile();
     
    	BufferedWriter output = new BufferedWriter(new FileWriter(files[i], true));
    	output.write("DKP_");
    	output.newLine();
    	output.write("+" + ((int)total));
    	output.close();
    				}  // For

    Where the method "findTotal" is written as follows:


    public static void findTotal (String fileName) throws IOException {
     
    		char operator = ' ';
    		int val = 0;
    		int total = 0;
    		System.out.println(fileName);
     
    		// Processes information to be stored in the file
    		try {
    			BufferedReader fileData = new BufferedReader(new FileReader(fileName));
    		String str;
    		fileData.readLine();
    		while ((str = fileData.readLine()) != null) {
    			operator = str.charAt(0);
    			if(operator == '+'){
    				val = Integer.parseInt(str.substring(1));
    				total += val;
    			}else if(operator == '-'){
    				val = Integer.parseInt(str.substring(1));
    				total -= val;
    			}  // If
     
    		}  // While
    	   	fileData.close();
    	}catch (IOException e){
    		System.out.println("IOException found.");
    	} // Catch
     
    	File targetFile = new File(fileName);
    	targetFile.delete();
    	targetFile.createNewFile();
     
    	BufferedWriter output = new BufferedWriter(new FileWriter(fileName, true));
    	output.write("DKP_");
    	output.newLine();
    	output.write("+" + total);
    	output.close();
     
    }  // Method: findTotal

    Something else I've noticed that I hadn't mentioned earlier: the findTotal() method doesn't appear to be executing the following lines of code, as the file is not rewritten between attempts.

    File targetFile = new File(fileName);
    		targetFile.delete();
    		targetFile.createNewFile();
     
    		System.out.println(total);
    		BufferedWriter output = new BufferedWriter(new FileWriter(fileName, true));
    		output.write("DKP_");
    		output.newLine();
    		output.write("+" + total);
    		output.close();
    Last edited by Mandraix; April 4th, 2011 at 04:03 PM. Reason: Solved.


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Trouble Reading Line in File

    Are there any exceptions being thrown while you are reading? This could result in the behavior you observe...

  3. #3
    Junior Member
    Join Date
    Mar 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Trouble Reading Line in File

    Quote Originally Posted by copeg View Post
    Are there any exceptions being thrown while you are reading? This could result in the behavior you observe...
    I haven't noted any exceptions as having been thrown at any point during the program's running. I'm completely lost on what the problem is here.

  4. #4
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Trouble Reading Line in File

    Can you kindly post through your whole code so that we could look over that and inside the findTotal() method, you used str.charAt(0), should it always check the character position at 0?
    Anyways, post your whole code, so that we could have a look. Thanks

  5. #5
    Junior Member
    Join Date
    Mar 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Trouble Reading Line in File

    Quote Originally Posted by Mr.777 View Post
    Can you kindly post through your whole code so that we could look over that and inside the findTotal() method, you used str.charAt(0), should it always check the character position at 0?
    Anyways, post your whole code, so that we could have a look. Thanks
    I'd been trying to keep it to what I thought was relevant, but I'll just post it in its entirety if you feel it will help.

    import java.io.*;
    import java.util.*;
     
    class GuildDKP {
     
    	final static String fileDirectory = "C:\\DKPFiles\\";
    	final static File dir = new File(fileDirectory);
     
    	public static void main (String str []) throws IOException {
    		System.out.println("\t\tWelcome to the GuildDKP program!\n");
     
    		menu();
     
    	} // Method: Main
     
    	public static void menu () throws IOException {
    		BufferedReader input = new BufferedReader (new InputStreamReader (System.in));
     
    		int menuChoice;
    		int menuFlag = 0;
     
    		System.out.println("\n\n\tPlease enter the number corresponding to your menu selection:\n");
     
    		System.out.println("1.) Create a new character file.");
    		System.out.println("2.) Input new DKP values.");
    		System.out.println("3.) Delete existing files.");
    		System.out.println("4.) Decay existing values.");
    		System.out.println("5.) Display the current priority list.");
    		System.out.println("6.) Backup existing files.");
    		System.out.println("7.) Populate files with random values.");
    		System.out.println("8.) Clear files of all existing values.\n");
     
    		while(menuFlag != 1) {
     
    			menuChoice = Integer.parseInt(input.readLine());
    			System.out.println();
     
    			switch(menuChoice) {
    				case 1:
    					menuFlag++;
    					createCharacterFile();
    					break;
    				case 2:
    					menuFlag++;
    					addNewValues();
    					break;
    				case 3:
    					menuFlag++;
    					deleteCharacterFiles();
    					break;
    				case 4:
    					menuFlag++;
    					decayCharacterFile();
    					break;
    				case 5:
    					menuFlag++;
     
    					break;
    				case 6:
    					menuFlag++;
     
    					break;
    				case 7:
    					menuFlag++;
     
    					break;
    				case 8:
    					menuFlag++;
     
    					break;
    				default:
    					System.out.println("Incorrect input.");
    					break;
    			} // Case
    		} // While
    	} // Method: Menu
     
    	public static void createCharacterFile () throws IOException {
    		BufferedReader input = new BufferedReader (new InputStreamReader (System.in));
     
    		System.out.println("Enter the name of the character whose value is to be stored.");
     
    		String fileName = fileDirectory.concat(input.readLine());
    		fileName = fileName.concat(".txt");
    	//	System.out.println(fileName);              Tests fileName
     
    		File newFile;
    		newFile = new File(fileName);
     
    		if(!newFile.exists()){
    			newFile.createNewFile();
    			System.out.println("\nNew file \"" + fileName + "\" has been created.");
    		} // If
     
    		// The following code applies the header which will signify the type of file
     
    		BufferedWriter output = new BufferedWriter(new FileWriter(fileName, true));
     
    		output.write("DKP_");
    		output.close();
    		System.out.println("\"" + fileName + "\" has been designated as a DKP file.");
     
    		menu();
     
    	} // Method: createCharacterFile
     
    	public static void addNewValues () throws IOException {
    		BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
     
    		String newValue = " ";
     
    		System.out.println("Please enter the name of the character whose file is to be edited.");
    		String fileName = fileDirectory.concat(input.readLine());
     
    		BufferedWriter output = new BufferedWriter(new FileWriter(fileName.concat(".txt."), true));
     
    		System.out.println("Enter the user's DKP values, please separate each input value by pressing enter.");
    		System.out.println("\t(Use the + or - prefixes to indicate postive/negative)");
    		System.out.println("\t\t\t(Enter 'x' to exit)");
     
     
    		// Inputs new values to file
    		while(!(newValue.equals("x"))){
    			output.newLine();
    			output.write(newValue);
    			newValue = input.readLine();
    		}  // While
    		output.close();
     
    		menu();
     
    	} // Method: addNewValues
     
     
    	public static void deleteCharacterFiles () throws IOException {
    		BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
     
    		System.out.println("Delete an individual file or delete all files? (1 - Individual, 2 - All)");
    		String userInput = input.readLine();
     
    		if(userInput.equals("1")){
    			System.out.println("Please enter the name of the character file to be deleted.");
    			String fileName = fileDirectory.concat(input.readLine());
     
    			File targetFile = new File(fileName.concat(".txt"));
     
    			System.out.println("Please confirm that you want to delete " + targetFile + ". \n \t (1 - Delete, 2 - Cancel)");
    			userInput = input.readLine();
     
    			if(userInput.equals("1")){
    				targetFile.delete();
    				if(!(targetFile.exists()))
    					System.out.println("The file has been deleted successfully.\n");
    				else
    					System.out.println("An error has occured in the deletion process.\n");
    				menu();
    			}  // If
    			else if(userInput.equals("2"))
    				menu();
    		}else if(userInput.equals("2")){
    			System.out.println("Please confirm that you want to delete all the files in " + fileDirectory + ". \n \t (1 - Delete, 2 - Cancel)");
    			userInput = input.readLine();
     
    			File[] files = dir.listFiles();
    			files = dir.listFiles();
     
    			if(userInput.equals("1")){
    				for(int i = 0; i<files.length; i++)
    					files[i].delete();
    				System.out.println("All files in " + fileDirectory + " have been deleted.");
    			}else if(userInput.equals("2"))
    				menu();
    		}else{
    			System.out.println("Incorrect input, forwarding to menu.");
    			menu();
    		}  // If
     
    	} // Method: deleteCharacterFiles
     
     
    	public static void decayCharacterFile () throws IOException {
    		BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
     
    		double decayVal = 0;
    		double total = 0;
     
    		System.out.println("Decay an individual file or decay all files? (1 - Individual, 2 - All)");
    		String userInput = input.readLine();
     
    		if(userInput.equals("1")){
    			System.out.println("Enter the name of the character whose values are to be decayed.\n");
    			String fileName = fileDirectory.concat(input.readLine());
     
    			System.out.println("Please confirm that you want to decay " + fileName + "'s values. \n \t (1 - Decay, 2 - Cancel");
    			if(userInput.equals("1")){
    				fileName = fileName.concat(".txt");
    				findTotal(fileName);
     
    				BufferedReader fileData = new BufferedReader(new FileReader(fileName));
     
    				fileData.readLine();
    				String totalString = fileData.readLine();
    				total = Integer.parseInt(totalString.substring(1));
    				System.out.println(total);
    				fileData.close();
     
    				System.out.println("Please enter the amount to decay the target files");
    				decayVal = Double.parseDouble(input.readLine());
     
    				total -= (total * (decayVal / 100));
    				System.out.println(total);
     
    				File targetFile = new File(fileName);
    				targetFile.delete();
    				targetFile.createNewFile();
     
    				BufferedWriter output = new BufferedWriter(new FileWriter(fileName, true));
    				output.write("DKP_");
    				output.newLine();
    				output.write("+" + ((int)total));
    				output.close();
    			}else if(userInput.equals("2"))
    				menu();
    			else{
    				System.out.println("Incorrect input, redirecting to menu.");
    				menu();
    			}  // If
    		}else if(userInput.equals("2")){
    			System.out.println("Please confirm that you want to decay all characters' DKP values in " + fileDirectory + " \n \t (1 - Decay, 2 - Cancel");
    			userInput = input.readLine();
     
    			if(userInput.equals("1")){
    				String[] files = dir.list();
     
    				System.out.println("Please enter the amount to decay the target files");
    				decayVal = Double.parseDouble(input.readLine());
     
    				for(int i = 0; i < files.length; i++){
    					findTotal(files[i]);
    					BufferedReader fileData = new BufferedReader(new FileReader(files[i]));
     
    					fileData.readLine();
    					String totalString = fileData.readLine();
    					total = Integer.parseInt(totalString.substring(1));
    					System.out.println("Total equals " + total);
    					fileData.close();
     
    					total -= (total * (decayVal / 100));
    			//		System.out.println(total);
     
    					File targetFile = new File(files[i]);
    					targetFile.delete();
    					targetFile.createNewFile();
     
    					BufferedWriter output = new BufferedWriter(new FileWriter(files[i], true));
    					output.write("DKP_");
    					output.newLine();
    					output.write("+" + ((int)total));
    					output.close();
    				}  // For
    			}else if(userInput.equals("2"))
    				menu();
    			else{
    				System.out.println("Incorrect input, forwarding to menu.");
    				menu();
    			}  // If
    		}else{
    			System.out.println("Incorrect input, redirecting to menu.");
    			menu();
    		}  // If
     
    		menu();
     
    	}  // Method: decayFiles
     
     
    	public static void findTotal (String fileName) throws IOException {
     
    		char operator = ' ';
    		int val = 0;
    		int total = 0;
    		System.out.println(fileName);
     
    		// Processes information to be stored in the file
    		try {
    			BufferedReader fileData = new BufferedReader(new FileReader(fileName));
    			String str;
    			fileData.readLine();
    		    while ((str = fileData.readLine()) != null) {
    				operator = str.charAt(0);
    				if(operator == '+'){
    					val = Integer.parseInt(str.substring(1));
    					total += val;
    				}else if(operator == '-'){
    					val = Integer.parseInt(str.substring(1));
    					total -= val;
    				}
     
    			}  // While
    	   		fileData.close();
    		}catch (IOException e){
    			System.out.println("IOException found.");
    		} // Catch
     
    		File targetFile = new File(fileName);
    		targetFile.delete();
    		targetFile.createNewFile();
     
    		BufferedWriter output = new BufferedWriter(new FileWriter(fileName, true));
    		output.write("DKP_");
    		output.newLine();
    		output.write("+" + total);
    		output.close();
     
    	}  // Method: findTotal
     
    } // Class: GuildDKP

  6. #6
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Trouble Reading Line in File

    1. Where are you getting menu choice?
    2. Are you sure that in file there is no space between your operator and the immediate operand?
    3. You better try using nextInt() or whatever type of values you have.
    4. And do you think it's a finite loop?

  7. #7
    Junior Member
    Join Date
    Mar 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Trouble Reading Line in File

    Quote Originally Posted by Mr.777 View Post
    1. Where are you getting menu choice?
    2. Are you sure that in file there is no space between your operator and the immediate operand?
    3. You better try using nextInt() or whatever type of values you have.
    4. And do you think it's a finite loop?
    1. Menu choice is from the user input at this line:
    menuChoice = Integer.parseInt(input.readLine());

    2. I am absolutely certain that there are no spaces between the operator and the operand in the text. All the files currently look like this:
    DKP_
    +64
    +64
    To clarify, there are no spaces after the "_" or either "4"'s. There is also no new line established after the second +64 on line 3.

    3. I'm using BufferedReader, which doesn't support the nextInt() function as does Scanner. The following lines of code assign the entire line (after the first character, to avoid including the operator) to a String, then converts that String to an integer. Again, this process worked fine for the first part of the decayCharacterValues() method, where only one file is being targeted. This should just be repeating the same process to the entire directory of files, so I'm not sure why it isn't working properly.

    val = Integer.parseInt(str.substring(1));
    total += val;

    4. The two loops in question, the for-loop in the decayCharacterValues() method and the while-loop in the findTotal() method both have set stopping points. The for-loop stops after it has gone through all the files in the directory and the while-loop stops when the next line has a value of something other than null.

    Something else I've noticed that I hadn't mentioned earlier on: the findTotal() method doesn't appear to be executing the following lines of code, as the file is not rewritten between attempts.

    File targetFile = new File(fileName);
    		targetFile.delete();
    		targetFile.createNewFile();
     
    		System.out.println(total);
    		BufferedWriter output = new BufferedWriter(new FileWriter(fileName, true));
    		output.write("DKP_");
    		output.newLine();
    		output.write("+" + total);
    		output.close();
    Last edited by Mandraix; April 4th, 2011 at 08:51 AM.

  8. #8
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Trouble Reading Line in File

    So, you can get text from your file into a string and try using nextInt(). Ain't you?

  9. #9
    Junior Member
    Join Date
    Mar 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Trouble Reading Line in File

    Quote Originally Posted by Mr.777 View Post
    So, you can get text from your file into a string and try using nextInt(). Ain't you?
    I'm not sure if I entirely understand, but doesn't my current method already do that in a different way?

  10. #10
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Trouble Reading Line in File

    So, you better try to use FileOutputStream and ObjectOutputStream (concept of serialization) in your function.

Similar Threads

  1. Writing to a specific line in a text file
    By The_Mexican in forum What's Wrong With My Code?
    Replies: 2
    Last Post: January 7th, 2011, 09:11 PM
  2. How can I detect the end of a line in a file ?
    By lumpy in forum Java Theory & Questions
    Replies: 3
    Last Post: February 18th, 2010, 03:13 AM
  3. Java program to read last line of a file
    By JavaPF in forum File Input/Output Tutorials
    Replies: 2
    Last Post: September 10th, 2009, 02:26 AM
  4. Reading a file line by line using the Scanner class
    By JavaPF in forum File Input/Output Tutorials
    Replies: 0
    Last Post: April 17th, 2009, 07:34 AM
  5. How to Read a file line by line using BufferedReader?
    By JavaPF in forum File Input/Output Tutorials
    Replies: 0
    Last Post: May 19th, 2008, 06:32 AM

Tags for this Thread