How do i create/modify the contents of a file before i create it in a Java program i have made?

StackOverflow https://stackoverflow.com/questions/20767984

  •  21-09-2022
  •  | 
  •  

Question

Hey here is my code i have created its a simple file creation program as i have only been using java for the past 2 days. I'm only 13 so please be simple :)

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Filecreator 
{
    public static void main( String[] args )
    {   
        Scanner read = new Scanner (System.in);
        String y;
        String u;


        try {
            System.out.println("Please enter the name of your file!");

            y = read.next();

            while (y.contains(".") || y.contains(",") || y.contains("{") || y.contains("}") || y.contains("@")){
                System.out.println("Your Filename contains an incorrect character you may only use Number 0-9 And Letters A-Z");
                System.out.println("Please Re-enter your file name");

                y = read.next();          
            }

            System.out.println("Please enter the file type name");

            u = read.next();

            while (u.contains(".") || u.contains(",") || u.contains("{") ||     u.contains("}") || u.contains("@") ){
                System.out.println("Your File-type name contains an incorrect character      you may only use Number 0-9 And Letters A-Z");
                System.out.println("Please Re-enter your file-type name");

                u = read.next();
            }


            File file = new File( y + "." + u );


            if (file.createNewFile()){
                System.out.println("File is created!");
            System.out.println("The name of the file you have created is called " + y +   file);
            }else{
                System.out.println("File already exists.");
            } 
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

If you run it on a program such as Eclipse you will see the output. But i want to be able to edit the [file's] contents before i finally choose the name and the file type and then save it. Is there anyway i can do this? Thanks - George

Was it helpful?

Solution 2

Read lines until the line contains a special end-of-file marker. Eg, the old unix program 'mail' append all lines until a line consisting of a single '.' is read.

// insert this before reading the filename
StringBuilder content = new StringBuilder();

s = read.next();

     while( !s.equals(".")) {
         content.append(s);
         content.append(String.format("%n"));
         s = read.next();
    }

The look at this: write a string into file (better answer than the other) and use that as an example of how to actually write the contents to the file, after it has been created.





p.s.

Pro-tip: I'm sure you have noticed that you have duplicated exactly the same line for checking if a filename is valid. A good programmer would notice this too and "extract" a method that does the logic in one place.

Example:

boolean isValidFilename( String s ) {
    return !(y.contains(".") || y.contains(",") || y.contains("{") || y.contains("}") || y.contains("@")));
}

You may then replace the checks;

while (!isValidFilename( u )){
    System.out.println("Your File-type name contains an incorrect character...etc");
}         

This is good since you don't have to repeat tricky code, which means there are fewer places to do errors in. Btw, the negations (!) are there to avoid negative names (invalid=true) because you might end up with a double negation when using them (not invalid=true) and that may be a bit confusing.

OTHER TIPS

Currently you are printing everything out to the console - this is done when you use System.out.println(...).

What you can do is to write the output somewhere else. How you can do this ? The easiest way how to do this is to Use StringBuilder:

http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html

This is a code sample :

StringBuilder sb = new StringBuilder();
sb.append("one ");
sb.append("two");
String output = sb.toString(); // output contains string "one two"

Now you have your whole output in one string. If you look at StringBuilder documentation (link is above) you can see that there are other useful methods like insert or delete that help you to modify your output before you convert it to string (with toString method). Once all your modifications are done you can write this string to a file.

For writing a String to a file this could be helpful :

How do I save a String to a text file using Java?

This is good enough approach if you are writing small files (up to few MB). If you want to write bigger files you shouldn't store the whole string in memory before you write it to a file. In such scenarios you should create smaller strings and write them to a file. There is a good tutorial for that :

http://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/

You can't edit a file before you create it. You can make changes to the data you are going to write to the file once you crate it; since you control both that data and the creation of the file, there should be no problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top