Reputation:
I'm working on an assignment that asks to request a file name, then take the file and output it to a .txt file with numbered line formatting like:
[001]
[002]
I have piece milled code together to get the program to work but I can't seem to get it to write in the requested format. Any help would be appreciated.
Here is my code so far.
try {
System.out.println("Enter your source code file name: ");
Scanner scanner = new Scanner(System.in);
String file = scanner.nextLine();
in = new FileInputStream(file);
out = new FileOutputStream(file + ".txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} catch (IOException e) {
System.out.println("Error!");
}
Upvotes: 0
Views: 63
Reputation: 720
You only need a counter to count your rows:
BufferedReader in = new BufferedReader(new FileReader(fileName));
BufferedWriter out = new BufferedWriter(new FileWriter(fileName + '.txt');
String line;
while ((line = in.read()) != -1) {
counter++;
out.write(String.format(..., counter, line)+"\r\n");
}
For additional information on the String.format()
method look at this link
Upvotes: 2
Reputation: 743
Try to use BufferedReader/BufferedWriter to read and write the lines of your text easier like this:
String txtName = "test";
String txtNumbered = "test1";
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(txtName+".txt")));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(txtNumbered+".txt")));
int count = 0;
String line = br.readLine();
while(line != null)
{
count++;
bw.write(count+" "+line+"\r\n");
line = br.readLine();
}
br.close();
bw.close();
}catch(IOException e)
{
System.out.println(e);
}
Upvotes: 1