0

I have a set of files, labeled file1.java, file2.java, ...

I want to pipe the output of the files to .txt files, such as output1.txt, output2.txt, etc. corresponding to each java file.

I know that I can do this by doing:

javac file1.java
java file1 > output1.txt

However, is there a way to do this of all files in a given directory? (instead of doing it manually)

user473973
  • 681
  • 2
  • 12
  • 23
  • You want to go through all *.java files, run each one and output to a txt file? I know for sure you can do this with a .bat (batch) file. Or you can pass in a filename as an argument to your java program to send any output to a text file -- another thought I know you can javac *.java you might see if you can do the same with java and us >> to append to a single file – Kairan Nov 27 '13 at 23:47
  • Yes that is correct. What would be a good resource for batch files? – user473973 Nov 27 '13 at 23:49

2 Answers2

1

This is a good for loop example:

Command line usage:

for /f %f in ('dir /b c:\') do echo %f

Batch file usage:

for /f %%f in ('dir /b c:\') do echo %%f

if the directory contains files with space in the names, you need to change the delimiter the for /f command is using. for example, you can use the pipe char.

for /f "delims=|" %%f in ('dir /b c:\') do echo %%f

If the directory name itself has a space in the name, you can use the usebackq option on the for:

for /f "usebackq delims=|" %%f in (`dir /b "c:\program files"`) do echo %%f

And if you need to use output redirection or command piping, use the escape char (^):

for /f "usebackq delims=|" %%f in (dir /b "c:\program files" ^| findstr /i microsoft) do echo %%f

It shows both command line + batch for loop examples. Then you will have the filenames and can just run some commands on those filenames like javac and java.

Just try to break it down to small tasks: Get list of files (all or just .class) Loop through each file and call javac and java on them

Google is your best friend - search for "DOS batch" + what you need

Community
  • 1
  • 1
Kairan
  • 4,722
  • 24
  • 57
  • 102
0

Your job is much easier if you restructure your output file names a bit: file1.java --> file1_output.txt

From the command line:

for %F in (*.java) do @javac "%F" >"%~nF_output.txt"

If in a batch file:

@echo off
for %%F in (*.java) do javac "%%F" >"%%~nF_output.txt"

If you keep your original naming convention, then you must parse out the number form each file name. Very doable, but it doesn't seem worthwhile in your case.

dbenham
  • 119,153
  • 25
  • 226
  • 353