• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Writing to a file

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey I'm working on a part of my program where it needs to write to a file. I need to use a file object to test that the file doesm't already exist and needs to reprompt for overwriting if it does exist. I was wondering if anyone could help based on these instruction from my project:

Prompt for the file name of the output file to write the formatted words to. Use a File object to test that the file doesn't already exist, and if it does, prompt to check for overwriting the file. Open the file for writing using a PrintWriter. Use a do-while loop to repeat these steps until a valid output file is entered.

Loop, reading words (text between whitespace) from the input file using Scanner.next(), appending them to a line of text being formatted, with one space character between words. Keep appending words until the current word would cause the line to become longer than the output column with. If so, write the line to the output file, reset it to contain just the new word, and continue reading. Continue reading until the end-of-file is encountered, using Scanner.hasNext().

I was trying to code it based on a tutorial but that one writes a line to a file hardcoded in the program. The biggest issue I'm having is the second instruction. Here is what I put together so far:



 
Greenhorn
Posts: 4
Firefox Browser Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Use the File method isFile: returns true if and only if the file denoted by the instance's abstract pathname exists and is a normal file; false otherwise
 
jay russ
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm really new to this so I don't know what you mean. Can you explain?
 
larry clay
Greenhorn
Posts: 4
Firefox Browser Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you want to verify if the file exists you'll need to use the isFile() instance method. Let me try to explain it (i'm also new to java and programming so we're together in this)

You're creating a File instance while creating & initializing the Scanner instance "scan":
Scanner scan = new Scanner(new File(inName));

If you want to work always on the same File you'll need to widen the scope of that instance, i'd suggest you create a null instance at the beginning of main() and then initialize/reinitialize when needed. Remember that File objects work with file and directory pathnames, for more info on the File class methods check this

the code you're looking for it's something like this


 
jay russ
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey sorry but I was having some trouble with another part of my program where it reads from a file before it writes to a new file. When I enter the file to read from it just doesn't do anything, it just brings the cursor to the next blank line. Could you tell me where my problem is? Here is just the section that tests if the file exists and reads from it if it does:

 
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the Ranch

I can’t see any code in your post which writes anything. I suggest you start in the Java Tutorials, where I think you will find what you need, and lots more.
 
jay russ
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I don't understand what is the problem with it. If I enter a file that exists it just does nothing. Does anyone see any problems with this? It all looks correct to me, this is really frustrating..
Here's the lastest code

 
Marshal
Posts: 28177
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you say it "does nothing" doesn't that just mean that it got to line 24 of your posted code and it's waiting for you to enter something else?

In fact I don't understand what the point of line 24 is anyway. You just went to a whole lot of trouble to confirm that the file name the user entered actually existed, and then you're throwing that name away and having the user enter it again?
 
jay russ
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
well it is supposed to read the file. Am I not doing this correctly? And yes when I say it does nothing it just goes to the next blank line waiting for the user to enter something.
 
Paul Clapham
Marshal
Posts: 28177
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

jay russ wrote:Am I not doing this correctly? And yes when I say it does nothing it just goes to the next blank line waiting for the user to enter something.



Of course you're not doing it correctly. If you were, your program would work and you wouldn't be here asking this question. But your program doesn't do what you want, so by definition you aren't doing it correctly.

Anyway I suggested there was something strange about line 24. I don't think you have responded to that. What is it supposed to do?
 
jay russ
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That is where it should open the file and read from it. This occurs after it checks that the file exists and can be read.
 
Paul Clapham
Marshal
Posts: 28177
95
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

jay russ wrote:That is where it should open the file and read from it.



We're talking about line 24 in your posted code, right? This line of code?

 
jay russ
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Oh ok I deleted that line and the program seems to be working fine now, thanks for the help. Now on to the next part!
 
jay russ
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This next part really has me clueless. I need to write to an output file that consists of the input file content formatted. It should read the words and ignore the spaces. No line can be longer than the max width that is entered at the beginning of the program. Any help getting this started would be great because I really have no idea. Here is all the code so it's easier to understand.

 
jay russ
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is anyone available to take a look at my previous post?
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

jay russ wrote:Is anyone available to take a look at my previous post?

Yes, but 160 lines of code with no indication of what you think the problem is will put people off replying. Go through some of the links on this page.
 
jay russ
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry I posted the whole program because I thought it would be easier for people to understand. Anyway I'm having issues with lines 136-149. I put in comments explaining what needs to go there. This section is to read words from the input file and append them to the current "line" being built. This occurs until the line and the newest word would exceed the column width. When the line is full it needs to write it to the output file, reset it to empty, and repeat this until the end of the file is encountered.
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Delete lines 141 and 155; they don’t do anything.
In the exit() method, why are you not using the junk String? Why are you reading nextLine()? That isn’t part of exiting.
What does that mean about length of line? Where do you get the length from? How are you measuring the length of the potential output (it is pretty easy)?
How are you putting several words together (hint: try here)?
You appear to be doing everything in the main method. The ideal length for a main method is one statement. You ought to move most of that code out into different methods. You should have a method which opens files, a method which reads, a method which adds to the output, a method which writes, etc. You should get one of them working (eg read) before you try anything else. You are trying to do too much all at once, and that doesn’t work. Break it into little pieces and then try.
When you get stuck about lengths, try working it out on paper. Not in code. Not until you know what it is supposed to do. Then you can convert it to code.

And despite what it says in some books, you should not use the \n character unless you have been told specifically that \n is required. You should find a brief explanation of that here, and it tells you what do instead.
 
jay russ
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm having a difficult time understanding how to read words from the input file. The length of the line for the output depends on whatever the user enters of the max width which is entered at the beginning of the program. It must be between 30 and 100, so say the user enters 40, then each line in the output cannot be greater than 40. If the last word in the line exceeds 40 then the line must end before that word and then that word is the first in the next line. I read what you suggested for reading words but I'm really new to java and I'm having a tough time understanding the concepts. Is it possible to help get me started with it or show me how it's used in another example?
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Start by highlighting lines 9 to 159 inclusive. Push the key with “del” written on.
Now you can actually create your application.
Get rid of that long main method. I think a main method has an ideal length . . . of one line.
Do it in stages.
Start by trying to read words. Create yourself a FileScanner class which has a java.io.File object as a field, and uses that File object to initialise a Scanner (or other means for reading). Give it one (public) constructor which takes the File object as a parameter. Give it methods like nextToken, nextInt, nextBigInteger, hasNextInt, hasNextToken, nextLine, etc. Comparison with the java.util.Scanner class will show that you are creating a “wrapper” round a Scanner object. all the methods I have suggested have counterparts with similar names in the Scanner class. You may suffer a FileNotFoundException in the constructor; that should be re-thrown not caught, so you have to use the throws keyword. You can read about re-throwing Exceptions here. You can also get the most recent Exception; there is a method in the Scanner class which returns that Exception.
Now you can test it like this:Note the way I have used args means, in my version, you must invoke it like thisYou must supply the name of the file, and the "" are to make sure the runtime doesn’ separate it into two on the space.

Now you have got that bit working, you can forget the FileReadingDemo class and work out how to put the individual words together. But that is for later. Don’t try to do it all at once. Get one part working and only then consider the next part.
You can read more about file reading here; the section about scanning tells you about Scanners. There is an example similar to what you want.
 
jay russ
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I understand that the way you are trying to show me is a much better way to code but I don't know how to use the created methods, in the main method. For instance the first part prompts for the width. I set the method up like this:



Now I don't know how to use it in the main method. I thought something like this:



I only have a couple days until this assignment is due so maybe it's better to just do it all in the main method. This is really difficult when you're not being taught.
 
jay russ
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can someone show me the correct way to open a Scanner object on a File object, and use the next() method to read each word? I can't figure this out. I put this together.

 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

jay russ wrote:Can someone show me the correct way to open a Scanner object on a File object, and use the next() method to read each word? I can't figure this out. I put this together.



Well, for starters, I don't see you calling next() anywhere. I see you're using Scanner in your code above, so you should at least be able to make a stab at it.

Also, naming a variable that's used for reading data in as out is not exactly the way to write clear, easy-to-understand code.

 
jay russ
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well I think this is correct but I don' t know where to go from here. I'm not sure what I do with "outputReader" or the printwriter variable "textoutWriter".


Also should I delete this line:


 
jay russ
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ok so my last problem with my program is formatting the text written to the output file. It reads from the input file which is obviously unformatted and then the output file displays it formatted. Now at this point the outpfile is displaying each word on its' own line. My goal is to print the text on one line until it reaches a certain length (entered by the user at the beginning) and then breaks to a new line. This should keep going until it reaches the end of the file.



This is the section where it displays each word on its own line:



What can I do with that to get it to do what I explained above?

 
jay russ
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Any suggestions for this?
 
jay russ
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I just need something to append "scan.next()" to a string and then get that string to break to a new line once it hits the max width entered by the user.

I think it would just be in this section that needs some altering:



I'm appending each word to the string "newReader" but I want it to read up to the max width, flush the string, and then read the next set of words and repeat this until the end of the file.
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No, that needs to be two methods (or three), not a section.
  • 1: You want one method which inspects the length of what you have got and what you are wanting to add. Call it something like canAddToString(String s)
  • 2: You want another method which adds the String to the current line, called if the lengths are OK.
  • 3: You want a method which writes the current text to your file. Then you can start adding Strings again.
  • Never use the + operator on Strings in several lines. You can use it as often as you like in one line because of an optimisation, but using it in several lines leads to performance problems. You need something different for repeated adding. Note its methods like append() return the same object, so you can join several method calls with multiple dots. Like this:-The easiest way to get rid of the text is to set the length to 0. It would be a good idea to pass the length of line required as a constructor argument, so as to set the initial capacity correctly.
     
    Don't get me started about those stupid light bulbs.
    reply
      Bookmark Topic Watch Topic
    • New Topic