-4

This program creates 10 files on my desktop. The issue I am having is with the file names. The first one created is called "SecretFile1". The second is "SecretFile12". The third is "SecretFile123". What changes should I make so that the file names are "SecretFile1", "SecretFile2", and "SecretFile3" respectively?

import java.io.*;

public class TextFiles {

    public static void main(String[] args) throws IOException {
        String doc = "SecretFile";
        int number = 0;
        for(i = 1; i <= 10;i++){

            number++;

            doc = doc + number;
            String name = "C:\\Users\\Soumil\\Desktop\\" + doc + ".txt";

            BufferedWriter bw = new BufferedWriter(new FileWriter("" + name + ""));
            bw.write("There's no secret.");
            bw.close();
       }
   }
}
user3370908
  • 29
  • 1
  • 7

2 Answers2

1

Use this code, it will work!

String doc = "SecretFile";
        String dump="";
           int number = 0;
           for(int i = 1; i <= 10;i++){

               number++;

               dump = doc + number;
               String name = "F:/src/" + dump + ".txt";

               BufferedWriter bw = new BufferedWriter(new FileWriter("" + name + ""));
               bw.write("There's no secret.");
               bw.close();
          }
Avag Sargsyan
  • 2,437
  • 3
  • 28
  • 41
Teejay
  • 11
  • 1
-1

For reading data from file, you can use this code

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class TextFiles {

    public static void main(String[] args) throws FileNotFoundException {
        FileInputStream fis = new FileInputStream("F:/input.txt");
        InputStreamReader input = new InputStreamReader(fis);
        BufferedReader br = new BufferedReader(input);
        String data;
        String result = new String();

        try {
            while ((data = br.readLine()) != null) {
                result = result.concat(data + " ");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(result);
    }
}
SkyWalker
  • 28,384
  • 14
  • 74
  • 132
  • Very poor code-only answer without any explanation. – Tunaki Feb 27 '16 at 17:13
  • I am an optimistic man. I have just tried to give him some quell, nothing else. Senior Bosses are already make this question as silly. :) When I was writing the answer, I know all people will give me curse...@Tunaki – SkyWalker Feb 27 '16 at 17:18
  • I have some words in my text.txt , but when I try to print n or h nothing comes out. – user3370908 Feb 27 '16 at 17:22
  • You would help him better by explaining what the code does, how it does it and what he needs to change and why. – Tunaki Feb 27 '16 at 17:22
  • Follow this - http://stackoverflow.com/questions/2864117/read-data-from-a-text-file-using-java @user3370908 It will help you. – SkyWalker Feb 27 '16 at 17:33