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.

Page 1 of 2 12 LastLast
Results 1 to 25 of 33

Thread: Java error discovered?

  1. #1

    Default Java error discovered?

    The problem is near the end - "Files.write(file1, charArray);" - only prints 1 line to the file. Tried 3 different ways of printing to file. This must be an error with Java.

    import java.io.*;
    import java.nio.file.*;
    import java.nio.charset.Charset;
     
    public class alphabetizer {
     
    	public static void main(String[] args) {
     
     
    		File file = new File("C:\\Documents and Settings\\Administrator\\My Documents\\unsorted_list.txt");
    		File file2 = new File("C:\\Documents and Settings\\Administrator\\My Documents\\sorted_list.txt");
    		StringBuffer contents = new StringBuffer();
    		BufferedReader reader = null;
    		BufferedReader reader1 = null;
    		int count = 0;
    		int listlength = 0;
    		String[] list = null;
    		String temp1 = null;
    		Path file1 =  FileSystems.getDefault().getPath("C:\\Documents and Settings\\Administrator\\My Documents\\", "sorted_list.txt");
    		byte[] charArray;
     
    		try {
           	       		reader = new BufferedReader(new FileReader(file));
    			reader1 = new BufferedReader(new FileReader(file));
    	       		String text = null;
     
    		        // repeat until all lines are read
     
                		while ((text = reader.readLine()) != null) {
    		                contents.append(text).append(System.getProperty("line.separator"));
    				count++;
                		}
     
    			list = new String[count];	
    			count = 0;
     
    			while ((temp1 = reader1.readLine()) != null) {
                  			list[count] = temp1;
    				count++;
                		}
     
    			listlength = count;
     
            	} catch (FileNotFoundException e) {
                		e.printStackTrace();
            	} catch (IOException e) {
                		e.printStackTrace();
            	} finally {
                		try {
                    	     if (reader != null) {
                                 reader.close();
                            }
               	} catch (IOException e) {
                   	        e.printStackTrace();
                           }
           		}
     
    		count = 0;
    		int count1 = 0;
    		String temp = null;
    		String temp2 = null;
    		String temp3 = null;
     
     
    		for ( count = 0 ; count < listlength ; count++ ) {	
    			temp = list[count];
    			for ( count1 = 0 ; count1 < count ; count1++ ) {	
     
    				temp2 = list[count1].toLowerCase(); 
    				temp3 = list[count].toLowerCase();
     
    				if ( (temp2.indexOf(45) == -1) && (temp3.indexOf(45) == -1) ) {
     
    					if ( temp2.compareTo(temp3) > 0) {
     
    					temp = list[count];
    					list[count] = list[count1];
    					list[count1] = temp;
    					count1++;
    					}	
     
    				} else {
     
    					if (temp2.indexOf(45) != -1) {
    						temp2 = list[count1].substring(0, list[count1].indexOf(45)).toLowerCase();
    						//System.out.println(list[count]);
    					} else {
    						temp2 = list[count1].toLowerCase();
    					}
     
    					if (temp3.indexOf(45) != -1) {
    						temp3 = list[count].substring(0, list[count].indexOf(45)).toLowerCase();
    					} else {					
    						temp3 = list[count].toLowerCase();
    					}
     
    					if ( temp2.compareTo(temp3) > 0) {
     
    						temp = list[count];
    						list[count] = list[count1];
    						list[count1] = temp;
    						count1++;
     
    					}
    				}
     
    			}
     
     
    		} 	
     
    		String temp5;
     
    		try {
     
    			for (int i = 0 ; i < listlength ; i++) {
     
    				//System.out.println(list[i]);
    				charArray = list[i].getBytes();
    				temp5 = new String(charArray);
     
     
    				//System.out.println(temp5);
     
    				Files.write(file1, charArray);	
     
    			}
     
    		}  catch (IOException e) {
    			System.out.println("IOException occurred");
    		}	
     
     
     
     	       // show file contents here
           	       //System.out.println(contents.toString());	
     
     
     
    	}	
     
    }
    Last edited by Programming_Hobbyist; October 25th, 2012 at 01:06 AM. Reason: please use [code] tags


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Java error discovered?

    I'm not entirely sure what your code is suppose to do. More likely than not, though, this is not a bug in Java, but an issue with your program. I can see several odd practices in your Java code.

    What is your program suppose to do? Do you have sample input files along with expected output vs. what you're getting (preferably something as short as possible which still demonstrates the issue)?

  3. #3

    Default Re: Java error discovered?

    The program takes a list of names and puts them in alphabetical order. I can tell you for sure, that everything works except for the printing to a file. Those commented out System.out.prints show that the list is fully alphabetized. When the file is printed out - all it shows is one name of the 397.

    I just tried it with a new list of 10 names - for some reason, the alphabetizing didn't work, nevertheless, the problem is the same - I can't write to file. Just copy all that up there to a file called alphabetizer.java (I can't attach files with this), and then I put this random list of names to a file, list_of_names.txt :

    Benita Abner
    Reed Kellam
    Jordon Seth
    Brittany Hellard
    Cyndi Liddle
    Princess Pickell
    Audrie Ehle
    Luvenia Pipes
    Astrid Rother
    Hermina Withers

    The file shows up in My Documents - but only the last line is present. You just need to change these 3 directories:

    File file = new File("C:\\Documents and Settings\\Administrator\\My Documents\\unsorted_list.txt");
    File file2 = new File("C:\\Documents and Settings\\Administrator\\My Documents\\sorted_list.txt");
    Path file1 = FileSystems.getDefault().getPath("C:\\Documents and Settings\\Administrator\\My Documents\\", "sorted_list.txt");
    Last edited by Programming_Hobbyist; October 25th, 2012 at 02:11 AM.

  4. #4

    Default Re: Java error discovered?

    Oh yes - unconventional programming. I basically taught myself how to program so, that explains it. Without any books.

  5. #5
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Java error discovered?

    It's a common reaction to "blame Java" when something unfamiliar happens. But think about it this way: which is more likely: you discovering a flaw that nobody else has found in a common API used by millions of people? Or that you just don't fully understand what the code is doing?

    I'm not trying to come off as judgmental, but it's a good practice to always blame yourself first: what am I misunderstanding here? What did I miss?

    I'd recommend you step through this with a debugger, or at least add some print statements, to figure out what's going on. Read through the APIs of everything you're using to make sure you aren't incorrectly assuming something. If you still can't figure it out, I suggest putting together an SSCCE that demonstrates exactly what you're talking about in as few lines as possible (which, in your case, should only be a few).
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  6. #6
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Java error discovered?

    Try abstracting your code. Break it up into smaller methods which each perform one task (for example, have a method which reads the file in, another one which takes a list of names and sorts them, and a third one which writes the file out). This will help you to analyze each section independent of the others to determine if they work as expected. It will also make your code much easier to read and decipher.

    There are a few things you can get rid of. For example, this:

    listlength = count;

    Arrays already have a length field (this isn't C or C++ where you need to track length separately). Use that instead. You don't need to manually set it or anything, it's automatically set when you create the array.

    As far as writing to a file goes, try using a PrintStream. This is the same output mechanism used by System.out and System.err and is my personal favorite for generic file output.

  7. #7

    Default Re: Java error discovered?

    Yes, a genuine Java error discovered. Printing to file doesn't work if you use a for loop to do it - the problem is the Try statement. It only allows runs once for instance - the last one. Thus - I've got to write the file all in one shot - if that's even possible.

    I'll contact Sun and Oracle.

  8. #8
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Java error discovered?

    Try what I suggested: abstract your code into separate methods.

    To write multiple lines to a file:

    public static void write_file(String filename) throws FileNotFoundException
    {
    	PrintStream out = new PrintStream(new FileOutputStream(filename));
    	out.println("first line.");
    	out.println("second line.");
    	out.println("third line.");
    }

    This prints out 3 lines of text to a given file. For example,

    public static void main(String[] args)
    {
    	try
    	{
    		write_file("test.txt");
    	}
    	catch (FileNotFoundException e)
    	{
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	}
    }

    Works perfectly fine for me. I'm running Windows 7, 64-bit with Java 1.7.0_03-b05.

  9. #9
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Java error discovered?

    Quote Originally Posted by Programming_Hobbyist View Post
    Yes, a genuine Java error discovered. Printing to file doesn't work if you use a for loop to do it - the problem is the Try statement. It only allows runs once for instance - the last one. Thus - I've got to write the file all in one shot - if that's even possible.

    I'll contact Sun and Oracle.
    Are you being sarcastic? I promise that this is not an actual bug- you're just misunderstanding something. Please post an SSCCE that demonstrates exactly what you're talking about in as few lines as possible.

    There are channels to report bugs, and they'll need an SSCCE as well, so you might as well let us check it over for you.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  10. #10

    Default Re: Java error discovered?

    I didn't try that - I didn't need to. I need to write hundreds of lines to a file.

  11. #11

    Default Re: Java error discovered?

    Yes - there's no easy way to write many lines to a file using a loop in Java. There might be a way, but I couldn't find it - perhaps bytebuffer can do it. I switched over to C++ - instantaneous success. An illustration as to why C++ is better.

  12. #12

    Default Re: Java error discovered?

    I already posted a SSCCE. The for statement doesn't print multiple lines to a file. It may be the try/catch that causes this java error.

  13. #13

    Default Re: Java error discovered?

    Try saving the following to testing.java. You'll see it writes to the file - but it only writes one line instead of 10. It does that with the three different methods of writing to a file that I've found. I'll send this error in Java's code to Sun/Oracle.


    import java.io.*;
    import java.nio.file.*;
    import java.nio.charset.Charset;
    import static java.nio.file.StandardCopyOption.*;
     
     
     
    public class testing {
     
    	public static void main (String[] args) {
     
    		Path file = FileSystems.getDefault().getPath("C:\\Documents and Settings\\Administrator\\My Documents\\", "sorted_list_1.txt");  
    		String temp = "hello";
    		byte[] chararray;
    		chararray = temp.getBytes();
     
    		try {
    			for ( int i = 0 ; i < 10 ; i++ ) {
     
    				//System.out.println(temp5);
    				Files.write(file, chararray);	
     
    			}
     
    		}  catch (IOException e) {
    			System.out.println("IOException occurred");
    		}	
     
     
    	}
     
    }
    Last edited by Programming_Hobbyist; October 25th, 2012 at 01:48 PM.

  14. #14
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Java error discovered?

    Quote Originally Posted by Programming_Hobbyist View Post
    I didn't try that - I didn't need to. I need to write hundreds of lines to a file.
    It's meant to be a short demonstration, it isolates the issue purely to file writing.

    	public static void write_file(String filename) throws FileNotFoundException
    	{
    		PrintStream out = new PrintStream(new FileOutputStream(filename));
    		for (int i = 0; i < 1000000; ++i)
    		{
    			out.println(i + " line.");
    		}
    	}

    This piece of code writes a million lines to a file using a for loop. Again, I have no problems.

    edit:

    I figured out what you're doing wrong. Relevant Javadoc:

    Writes bytes to a file. The options parameter specifies how the the file is created or opened. If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0. All bytes in the byte array are written to the file. The method ensures that the file is closed when all bytes have been written (or an I/O error or other runtime exception is thrown). If an I/O error occurs then it may do so after the file has created or truncated, or after some bytes have been written to the file.
    Your file code isn't appending because you never specified that it should append. Rather, you're continually opening up the file, truncating the file to 0 size, writing to it, closing the file, then repeating the process.
    Last edited by helloworld922; October 25th, 2012 at 01:54 PM.

  15. #15

    Default Re: Java error discovered?

    Yes the problem is the Try/Catch statement. Throws solves it. Problem solved - but it's still an error.

  16. #16
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Java error discovered?

    see the edit to my response... it shows that this isn't a problem in Java, just a misunderstanding of what Files.write() does.

  17. The Following User Says Thank You to helloworld922 For This Useful Post:

    curmudgeon (October 25th, 2012)

  18. #17
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Java error discovered?

    Quote Originally Posted by Programming_Hobbyist View Post
    Yes the problem is the Try/Catch statement. Throws solves it. Problem solved - but it's still an error.
    No, it isn't an error, and you're wrong that it has anything to do with the try, catch, or throw statement. This works fine for me too:

    	public static void write_file(String filename)  
    	{
    		try{
    			PrintStream out = new PrintStream(new FileOutputStream(filename));
    			for (int i = 0; i < 1000000; ++i)
    			{
    				out.println(i + " line.");
    			}
    		}
    		catch(FileNotFoundException e){
    			e.printStackTrace();
    		}
    	}

    If you really want to convince us, provide an SSCCE - take out all your extra logic and concentrate only on the issue at hand, as helloworld and I did.

    Chances are you're either misunderstanding the API or your code is doing something different from what you assume it's doing. The only way to be sure is to put together a little example.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  19. The Following User Says Thank You to KevinWorkman For This Useful Post:

    curmudgeon (October 25th, 2012)

  20. #18
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Java error discovered?

    Quote Originally Posted by Programming_Hobbyist View Post
    It only allows runs once for instance - the last one.
    Ya what he said...

  21. #19

    Default Re: Java error discovered?

    There's was a ghost in my machine. I tried that printstream before, and several others, and none worked. Would simply not write anything to the file. I've met this phenomenon before - with Microsoft Visual Studio 2010. It was giving me an error - couldn't find the include file "stdafx.h" when trying to create a Windows Form application file - then it just vanished somehow, after I found a way around it (first compiling with just that include file...then compiling with the other include files).

    But now I've encountered success. Both solutions work, but then that doesn't explain those errors Java was giving me. For the Files.write, when there's no existing file - it should still work but it doesn't. When setting it to append - then it works for some reason. Without the append option, it creates one; it doesn't need to truncate it to 0 if it doesn't exist or open an initial. Thus - there's an error with append, and not the Try/Catch. This same problems exists for:

    Outputstream out - out.write
    BufferedWriter writer - writer.write
    Files.write

    They are basically the same method.

    I tried printstream just now, by putting it into a different method, and calling that method from the main method, with a try/catch to catch the IOException error. That didn't work - it only printed the last line. However, I tried it in the public static main, with a throws right next to "public static void main", and without the try/catch, and then it worked. But then I switched back to the first way, putting it in a different method, calling it from the main method with a try/catch statement, and now that one worked. There's a ghost in my machine.

    So problem solved. This was highly unusual behavior from my computer - not really human error.

  22. #20

    Default Re: Java error discovered?

    It's entirely possible that with my latest attempt at making the printstream with my main program - that I might've compiled a different, earlier version of these programs (possibly the brief example that I posted here with append), and when I tried that method again after getting it to work in the main method, then it worked correctly. Thus explaining that paradox. However - we have discovered an error with those write methods. As for my first attempts yesterday at printing without other methods - I must've tried some outdated/deprecated methods, and not that one.

  23. #21
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Java error discovered?

    I stand by my statement that this is almost definitely not a "Java error". You've listed several sources of potential human error, and nobody (including you) is able to reproduce your original problem. This is exactly why we ask for an SSCCE- it forces you to check all of your assumptions, including about which version of your own code you're running.

    I would guess that the ghost in your machine is in fact a result of some misunderstanding about what the code was doing, and then a misunderstanding about which code you were actually running. Again, not a Java error. This is why I suggested that you shouldn't jump to that conclusion before checking all of your assumptions.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  24. #22

    Default Re: Java error discovered?

    Helloworld992 helped me figure it out - there's something wrong with .write. There's something call the scientific method. If something is obviously wrong - you tend to accept that as fact.

  25. #23
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Java error discovered?

    All HelloWorld did was point out your misunderstanding of Java, not that there is an intrinsic error within Java that you've magically just discovered. But go on and continue living in whatever fantasy world makes you happy.

  26. The Following User Says Thank You to curmudgeon For This Useful Post:

    KevinWorkman (October 25th, 2012)

  27. #24

    Default Re: Java error discovered?

    Well thanks everyone for the help. Why do you people even post on this forum? Is it the social aspect? It must be the social aspect. Anyway - this is part of my larger project. Now that I can write to file, I can save data to a file, and then retrieve that data. I'm building a project where I can add people, their attributes, and then easily sort them according to attributes, for instance weight, height, eye-color, etc, and then show images of these people according to the sorting criteria.

  28. #25
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Java error discovered?

    Quote Originally Posted by Programming_Hobbyist View Post
    Helloworld992 helped me figure it out - there's something wrong with .write. There's something call the scientific method. If something is obviously wrong - you tend to accept that as fact.
    Hahahaha, no, you tend to try to repeat the experiment! If you (and others) can't repeat the results, then something must have been wrong with your original findings. In this case, you made an error in the code or in your assumptions. And that's fine, it happens to every single one of us, which is why it's not very wise to conclude that you found a major bug in Java every time.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 0
    Last Post: July 2nd, 2012, 09:11 PM
  2. Java Error cannot be applied to (java.lang.String), phone book entry program.
    By iceyferrara in forum What's Wrong With My Code?
    Replies: 5
    Last Post: September 23rd, 2011, 06:32 AM
  3. [SOLVED] Java run time error: 'java.lang.NullPointerException"
    By ChandanSharma in forum What's Wrong With My Code?
    Replies: 9
    Last Post: June 20th, 2011, 11:53 AM
  4. A Java Error
    By Shyamz1 in forum Java Theory & Questions
    Replies: 9
    Last Post: October 7th, 2010, 07:56 AM
  5. Is it possible to load classes at runtime that are discovered from a directory
    By mydarkpassenger in forum Java Theory & Questions
    Replies: 11
    Last Post: June 10th, 2010, 10:33 AM