aspose file tools*
The moose likes Beginning Java and the fly likes read and write from txt file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "read and write from txt file" Watch "read and write from txt file" New topic
Author

read and write from txt file

Um Hassan
Greenhorn

Joined: Jun 16, 2009
Posts: 10
I want to write a method that returns a list person with duplicates name. The list of name can be read from file “person.txt”. The out is at “duplicate.txt”.
-------------------
“person.txt”
ali
rahman
muath
rahmat
rahman
ali
safa
safa
------------------
“duplicate.txt”
rahman
ali
safa
------------------
I tried by this code... it isn't work correctly, could anyone get the errors,please?


import java.io.*;
class FileRead
{
public static void main(String args[])
{
//------------------Open person.txt file---------
try
{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("person.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}
catch (Exception e)
{
//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
// Stream to write file
FileOutputStream fout;
//------------------Open duplicate.txt file---------
try
{
// Open an output stream
fout = new FileOutputStream ("duplicate.txt");

// Print a line of text
new PrintStream(fout).println ("rahman ali safa");

// Close our output stream
fout.close();
}
// Catches any error conditions
catch (IOException e)
{
System.err.println ("Unable to write to file");
System.exit(-1);
}
}
}


-------------------------------, Cheers
James Dixon
Ranch Hand

Joined: Jun 20, 2009
Posts: 32
Hi Um

The only thing I can see is that the main method isn't quite correct. It should read:
rather than:

If this isn't the problem, can you provide the stack trace?

James
p.s. in future could you include any code you provide '[code]' tags as it's a little easier to read, cheers :-)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
Writing (String[] args) is better, but that shouldn't stop the application running. Please have a look at this FAQ, Um Hassan. Also your code is hard to read without code tags. Tell us what actually happens.
Peter Miklosko
Ranch Hand

Joined: May 26, 2009
Posts: 76
Um Hassan wrote:
I tried by this code... it isn't work correctly, could anyone get the errors,please?

Sorry I do not see any errors it is working fine, but obviously there is no de-duplication method just hard coded file writing solution. So either you are struggling to write de-duplication method, or you are having some unforeseen problems we cannot work out as you failed to provide any error messages that you may received.
Please clarify.

James Dixon wrote:
rather than:

Putting brackets with variable rather then variable type is common beginner mistake (or I would say approach when people moving from different programming language like C++) that I seen many teacher doing this way and certainly few professional developers . So it is not an error
Um Hassan
Greenhorn

Joined: Jun 16, 2009
Posts: 10
Sorry if I confused you. However, my code isn't answer the requirement. I tried to apply "read"and "write" steps ,but certainly without re-write a duplicate words...? So... How I can do my code effectively. Thanks
Um Hassan
Greenhorn

Joined: Jun 16, 2009
Posts: 10
“duplicate.txt”
rahman
ali
safa
----------------- this is a duplicate file
but when we open the file in the code we just print ("rahman ali safa"); and I didn't duplicate it?

// Print a line of text
new PrintStream(fout).println ("rahman ali safa");
Peter Miklosko
Ranch Hand

Joined: May 26, 2009
Posts: 76
Required change can be done simple as this
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
Peter Miklosko, thank you for the answer, but we don't like straight answers like that. Please read this FAQ and also what it says at the top of the beginner's forum:
We're all here to learn, so when responding to others, please focus on helping them discover their own solutions, instead of simply providing answers.
It does no good, simply depriving posters of the opportunity to learn from themselves.

Please don't be annoyed, but I am pulling rank and deleting your solution.
Peter Miklosko
Ranch Hand

Joined: May 26, 2009
Posts: 76
You absolutely right, my bad and I'm sorry. Lets re-word my proposed solution.

Hassan, at this moment you read a file and just print out what ever been read. What you need to add is some temporary holder/storage facility where all read data could be stored and recalled once need it. I would recommend to go with ArrayList as in comparison to Array. ArrayList does not need declaration of size before you can enter any data and it is able to dynamically adjust to size changes (in the future you may get file that has more then 8 entries and with Array you would need to edit your application each time the size would change). So open file, read the file (use of String.trim() method would be handy), store the data in ArrayList and then close any readers or streams you used (in original code you for example did not close DataInputStream and BufferedReader)

De-duplication
  • Create another ArrayList to keep found duplicates.
  • Use for loop to iterate through ArrayList holding read data.
  • Get single element from ArrayList at position dictated by current position of the for loop for(int i = 0; ....).
  • Check if this element is already in your duplicate ArrayList, if does not exists continue, else skip the whole process and let the for loop increment. (ArrayList method indexOf(Object o) could help you)
  • Check selected element against rest of the elements of "read data" ArrayList and see if it is stored in any other position (Another method of ArrayList comes in play lastIndexOf(Object o) )


  • Once through de-duplication just modify your existing writing code to accommodate retrieving data from your duplicate ArrayList and passing them to printStream
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39396
        
      28
    Thank you, but there is a much simpler way to do it. How you go about it depends on how much you are supposed to use ready-made code (what you would do in real life) and to what extent you are supposed to code your own low-level algorithms.

    I shall give a hint how I would do it: I would use something you can find if you read this Java™ Tutorials section. The sections tell you what happens about duplicates.

    By the way: Um Hassan, you were not at all clear about your requirements at first.
    Um Hassan
    Greenhorn

    Joined: Jun 16, 2009
    Posts: 10
    Peter Miklosko,and Campbell Ritchie thank you for helping me. I'll do my best to get the solution via your comments.
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 39396
        
      28
    You're welcome Please tell us how you get on.
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: read and write from txt file