Click here to Skip to main content
15,889,867 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am not able to write the contents to the file in java. Please help:

//Reads an input file containing numbers or strings and sorts them and writes to a new file
import java.io.*;
import java.util.*;

public class FileSort
{
	private Scanner input;
	private Formatter output;
        private List<Integer> list;

	private void openFile(String fileName)
	{
		try{
			input = new Scanner(new File(fileName));
		}

		catch(FileNotFoundException fileNotFoundException)
		{
			System.err.println("Error opening the file. File Not Found");
			System.exit(1);
		}
	}

	private void readFile(String fileName)
	{
		try{
                    list = new ArrayList<Integer>();
                    while(input.hasNext())
                    {
                        list.add(Integer.valueOf(input.next()));
                    }
                    Collections.sort(list);
                    //System.out.printf("\nThe list is: %s",list);
		}
		
		catch(NoSuchElementException elementException)
		{
			System.err.println("File improperly formatted.");
			input.close();
			System.exit(1);
		}
	}

	private void writeFile(String fileName)
	{
		try{
                    output = new Formatter(fileName);
		    output.format("%s", "Hello");
		}
		
		catch(Exception e)
		{
			System.err.println(e.getMessage());
			output.close();
			System.exit(1);
		}
	}
	
	public static void main(String[] args)
	{
		FileSort fs = new FileSort();
		fs.openFile("input.txt");
		fs.readFile("input.txt");
		fs.writeFile("output.txt");
	}
}
Posted
Comments
Sergey Alexandrovich Kryukov 14-Apr-14 1:02am    
What's the problem? "I am not able" is not informative.
—SA

You are not attempting any file operations in writefile

C#
try{
                    output = new Formatter(fileName);
            output.format("%s", "Hello");
        }


You are formatting the string filename, then overwriting that format with a new string. No file operations.

Have a read of this

http://www.homeandlearn.co.uk/java/write_to_textfile.html[^]

Hope it helps.

/Darren
 
Share this answer
 
You need to use FileReader and FileWriter. For example:
C#
try {
            FileWriter writer = new FileWriter("output.txt");
            writer.write("hello");
            writer.flush();
            writer.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900