Reputation: 509
I would like to know how I can convert standard input to a string. For instance, I have a txt file with n amount of letters - all these I want to read into one string.
Just to make sure: standard input is when you give the program a .txt as input.
Help would be appreciated!
Upvotes: 2
Views: 9748
Reputation: 509
I end up using this:
String s = "";
while (!StdIn.isEmpty()){
s = s + StdIn.readChar();
}
I ran the program using: java program < a.text
Upvotes: 1
Reputation: 208
First, do you want to give a filename as a argument with your program. Or the whole file as input? In the first case you do:
"program filename.txt"
In the second you input:
"program < filename.txt".
In the first case the filename is the input. And your program will have to open a file itself. In the second case the contents of the file are given as input of the file.
If you only give the filename, the filename is in the arguments of your main function (the array args of the "main(String args[])" part. Using this filename you can then use the earlier suggested readFileToString to convert the contents of the file into a string.
If you want to use the other method of file input "program < filename.txt", use the a InputStream for that. See the documentation for more information about InputStream http://download.oracle.com/javase/6/docs/api/java/io/InputStream.html
You also mention you are rather new to Java. I hope you do know of the existence of the java documentation? http://download.oracle.com/javase/6/docs/api/index.html contains a lot of information you might want to know.
Upvotes: 0
Reputation: 420951
I have a file and I want to store the data of it in a string.
This can be done using commons-io
:
String content = FileUtils.readFileToString(file);
To read from stdin to a string, you could use a scanner. Use while (scanner.hasNextLine())
if you want the entire file.
String firstLineFromStdin = new Scanner(System.in).readLine();
Upvotes: 3
Reputation: 53496
What you want to do is pipe the file into your application...
java your.package < file.txt
Then you can read the file as normal via Java's System.in.
Upvotes: 0
Reputation: 108947
You could try something like
System.setIn(new FileInputStream(filename));
Here's an example on redirecting standard i/o
Upvotes: -1