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!
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);
(complete example)
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();
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.
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.
I end up using this:
String s = "";
while (!StdIn.isEmpty()){
s = s + StdIn.readChar();
}
I ran the program using: java program < a.text
You could try something like
System.setIn(new FileInputStream(filename));
Here's an example on redirecting standard i/o
Related
TL;DR
Why does reading in a file with – not find any data on Notepad?
Problem:
Up to this point, I have been using just plain ol' Notepad (Version 6.1) to read/write text for testing/answering questions here.
Simple bit of code to read in the text files contents, and print them to the console:
Scanner sc = new Scanner(new File("myfile.txt"));
while (sc.hasNextLine()) {
String text = sc.nextLine();
System.out.println(text);
}
All is well, the lines print as expected.
Then, if I put in this exact character: –, anywhere in the text file, it will not read any of the file, and print nothing to the console.
I can of course use Notepad++ or other (better) text editors, and there is no issue, the text, including the dash character, will print as expected.
I can also specify UTF-8, using Notepad, and it will work fine:
File fileDir = new File("myfile.txt");
BufferedReader in = new BufferedReader(
new InputStreamReader(
new FileInputStream(fileDir), "UTF8"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
On my original Notepad file, if I copy and paste the text (including the –) into Notepad++ and compare the two files with WinMerge, it tells me that the dash on Notepad is –, but on Notepad++, it is –.
Question:
Why, when this – is used in a text file in Notepad, it reads nothing, basically telling me that hasNextLine() is false? Should it not at least read the input until the line that contains this specific character?
Steps to reproduce:
On Windows 7, right-click and create new Text Document.
Put any text in the file (without any special characters, as such)
Put in this character anywhere in the file: –
Run the first block of code above
Output: BUILD SUCCESSFUL (total time: 1 second), i.e. doesn't print any of the text.
PS:
I know I asked a similar (well, it ended up being the same) question yesterday, but unfortunately, it seems I may not have explained myself well, or some of the viewers didn't fully read the question. Either way, I think I've explained it better here.
The issue seems to be a difference of encoding. You have to read in the same encoding that the file was written into.
Your system notepad probably uses Windows-1252(or Cp-1252) encoding. There have been problems in this encoding with a range of characters between 128 - 159. The Dash lies between this range. This range is not present in the equivalent ISO 8859-1, and is only present in the Cp1252 encoding.
Eclipse, when reading the notepad file, assumes the file to be having the encoding ISO-8859-1 (as it is equivalent). But this character is not present in ISO-8859-1, hence the problem. If you want to read from Java, you will have to specify Cp1252, and you should get your output.
This is also the reason why your code with UTF-8 works correctly, when the file in notepad is written in UTF-8.
A buffered reader reads more than the current line, maybe the text upto the problematic bytes. Charset.CharsetDecoder.onMalformedInput then comes in play, and there something restricive happens, which I would normally not have expected.
Do you use a special JDK? Do you wipe exceptions under the carpet? Like a lambda wrapping the above code. (Add catch Throwable)
Is your platfom encoding -Dfile.encoding=ISO-8859-1 instead of Cp1252.
Am aware that
FileOutputStream out = new FileOutputStream(file_name, true);
allows appending rows to a file. Is there a way to append columns of data to a non-empty text file starting from the first row?
For e.g., file.txt contains:
Name Address
ABC OtherLand
Can we later modify file.txt to be:
Name Address PhoneNumber
ABC OtherLand 3333333333
I've heard of the awk command in Unix. If there isn't a way to do this directly in the java programming language, would appreciate if someone could share code-bits on calling awk using java syscalls.
Thanks!
No you can't. There is no such option. You can always open a file to read, write or append content to it.
To achieve this, you will need to
Read each line of a file
Append the content to each line.
Write to a temporary file
Can anyone tell me how to cope with illegal file names in java? When I run the following on Windows:
File badname = new File("C:\\Temp\\a:b");
System.out.println(badname.getAbsolutePath()+" length="+badname.length());
FileWriter w = new FileWriter(badname);
w.write("hello world");
w.close();
System.out.println(badname.getAbsolutePath()+" length="+badname.length());
The output shows that the file has been created and has the expected length, but in C:\Temp all I can see is a file called "a" with 0 length. Where is java putting the file?
What I'm looking for is a reliable way to throw an error when the file can't be created. I can't use exists() or length() - what other options are there?
In that particular example, the data is being written to a named stream. You can see the data you've written from the command line as follows:
more < .\a:b
For information about valid file names, look here.
To answer your specific question: exists() should be sufficient. Even in this case, after all, the data is being written to the designated location - it just wasn't where you expected it to be! If you think this case will cause problems for your users, check for the presence of a colon in the file name.
I would suggest looking at Regular Expressions. They allow you to break apart a string and see if certain characteristics apply. The other method that would work is splitting the String into a char[], and then processing each point to see what's in it, and if it's legal... but I think RegEx would work much better.
You should take a look at Regular Expressions and create a pattern which will match any illegal character, something like this:
String fileName = "...";
Pattern pattern = Pattern.compile("[:;!?]");
Matcher matcher = pattern.match(fileName);
if (matcher.find())
{
//Do something when the file name has an illegal character.
}
Note: I have not tested this code, but it should be enough to get you on the right track. The above code will match any string which contains a :, ;, `!' and '?'. Feel free to add/remove as you see fit.
You can use File.renameTo(File dest);.
Get the file name first:
String fileName = fullPath.substring(fullPath.lastIndexOf('\\'), fullPath.length);
Create an array of all special chars not allowed in file names.
for each char in array, check if fileName contains it. I guess, Java has a pre-built API for it.
Check this.
Note: This solution assumes that parent directory exists
I decided to create a currency converter in Java, and have it so that it would pull the conversion values out of a text file (to allow for easy editability since these values are constantly changing). I did manage to do it by using the Scanner class and putting all the values into an ArrayList.
Now I'm wondering if there is a way to add comments to the text file for the user to read, which Scanner will ignore. "//" doesn't seem to work.
Thanks
Best way would be to read the file line by line using java.io.BufferedReader and scan every line for comments using String#startsWith() where in you searches for "//".
But have you considered using a properties file and manage it using the java.util.Properties API? This way you can benefit from a ready-made specification and API's and you can use # as start of comment line. Also see the tutorial at sun.com.
Scanner wont ignore anything, you will have to remove the comments from your data after you have read it in.
Yea, while ((currentLine = bufferedReader.readLine()) != null) is possibly the easiest, then perform your necessary tests. currentLine.split(regex) is also very handy for converting a line into an array of values using a delimiter.
With Java nio, you could do something like this. Assuming you want to ignore lines that start with "//" and end up with an ArrayList.
List<String> dataList;
Path path = FileSystems.getDefault().getPath(".", "data.txt");
dataList = Files.lines(path)
.filter(line -> !(line.startsWith("//")))
.collect(Collectors.toCollection(ArrayList::new));
me and my buddy are working on a program for our Object Oriented Programming course at college. We are trying to write text into a file as a database for information. The problem is that when we try to read the corresponding lines with BufferedReader we can't seem to figure out how to read the correct lines. The only functions avaliable seem to be read(), which reads a character only. readLine() reads only a line(not the line we want it to read. skip() only skips a number of characters specified. Anyone have an idea how we could tell the program what line we want to read? Our method getAnswer() with the argument int rowNumber is the one we are trying to do:
Superclass: http://pastebin.com/d2d9ac07f
Subclass is irrelevant(mostly because we haven't written it yet).
Of course it is Java we are working with.
Thanks beforehand.
You will have to use readLine(), do this in a loop, count the number of lines you've already read until you've reached the line number that you want to process.
There is no method in BufferedReader or other standard library class that will read line number N for you automatically.
Use the Buffered Readers .readLine(); method until you get to the data you need. Throw away everything you don't and then store the data you do need. Granted this isn't effiecent it should get your job done.
readLine() in Java simply reads from the buffer until it comes upon a newline character, so there would really be no way for you to specify which line should be read from a file because there is no way for Java to know exactly how long each line is.
This reason is also why it's difficult to use skip() to jump to a particular line.
It might be better for you to loop through lines using readLine(), then when your counter is where you'd like it to be, begin processing.
String line = myBufferedReader.readLine();
for(int i = 1; i < whichLine && line != null; i++){
line = myBufferedReader.readLine();
}
/* do something */