furquan ahmad
furquan ahmad

Reputation: 33

Set predefined text to a file when writing to it in Java

I'm new to Java. I'm trying to write details to a file but i want to have predefined text in the file such as:
Name:
Age:
City:
Sport:

I wasn't too sure on how to do this. I'm trying to use a switch statement and depending on the position of the array it will write the predefined text first then fill it with the relevant information. I wanted to put the switch statement in another method to reduce the lines of code in the method, but i wasn't too sure how to return i whilst inside the for loop

	
  private String setPredefinedFileLines() { 
	  int i = 0; String
	  startOfFileText = null; switch (i) { 
	  case 1: startOfFileText =
	  "Server Name :  "; break; }
  
	  return startOfFileText;
  
	 }

public void writeStringToFile(String[] stringContents) throws IOException {
		BufferedWriter bw = new BufferedWriter(new FileWriter(fileToWriteTo));

		try {

			for (int i = 0; i < stringContents.length; i++) {
				String startOfFileText = null;
				switch (i) {
				case 1:
					startOfFileText = "Server Name :  ";
					break;
				}
				bw.write(stringContents[i]);
				bw.newLine();
				bw.flush();
			}
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}

		finally {
			if (bw != null) {
				bw.close();
			}
		}

	}

Upvotes: 0

Views: 82

Answers (2)

user6281371
user6281371

Reputation:

Try this.

import java.io.*;

public class SampleApp {
    public static void main(String... args) throws IOException {
        // For purposes of demonstration values are hardcoded.
        String name = "Desmond";
        int age = 24;
        String city = "New York";
        String sport = "Basketball";

        String fileName = "output.txt";

        writeToFile(name, age, city, sport, fileName);
    }


    public static void writeToFile(String name, int age, String city, String sport, String fileName) throws IOException {
        File fileToWriteTo = new File(fileName);
        fileToWriteTo.createNewFile();

        try (PrintWriter pw = new PrintWriter(fileToWriteTo)) {
            pw.println("Name: " + name);
            pw.println("Age: " + age);
            pw.println("City: " + city);
            pw.println("Sport: " + sport);
        }
   }
}

However, it is wiser to bundle name, age, city, and sport in another class, like this:

public class Info {
    public String name;
    public int age;
    public String city;
    public String sport;


    Info(String name, int age, String city, String sport) {
        this.name = name;
        this.age = age;
        this.city = city;
        this.sport = sport;
    }
}

and do this instead.

import java.io.*;

public class SampleApp {
    public static void main(String... args) throws IOException {
        // For purposes of demonstration values are hardcoded.
        Info info = new Info("Desmond", 24, "New York", "Basketball");

        String fileName = "output.txt";

        writeToFile(info, fileName);
    }


    public static void writeToFile(Info info, String fileName) throws IOException {
        File fileToWriteTo = new File(fileName);
        fileToWriteTo.createNewFile();

        try (PrintWriter pw = new PrintWriter(fileToWriteTo)) {
            pw.println("Name: " + info.name);
            pw.println("Age: " + info.age);
            pw.println("City: " + info.city);
            pw.println("Sport: " + info.sport);
        }
   }
}

Upvotes: 0

viveksinghggits
viveksinghggits

Reputation: 680

Here is the complete working code

public class WriteToFile {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception{
        File file = new File("file.out");
        BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
        List<Student> students = new ArrayList<Student>();
        Student s1 = new Student("Vivek", "23", "Pune", "Cricket");
        Student s2 = new Student("Vivek", "23", "Pune", "Cricket");
        Student s3 = new Student("Vivek", "23", "Pune", "Cricket");

        students.add(s1);
        students.add(s2);
        students.add(s3);

        for(Student s: students){
            bw.write("Name:"+s.name+"\n");
            bw.write("Age:"+s.age+"\n");
            bw.write("City:"+s.city+"\n");
            bw.write("Sport:"+s.sport+"\n");
        }


        bw.close();
    }

}

class Student{
    String name, age, city, sport;

    public Student(String name, String age, String city, String sport){
        this.name = name;
        this.age = age;
        this.city = city;
        this.sport = sport;
    }
}

Code is quite simple but let me know if you are not able to understand.

Upvotes: 1

Related Questions