I need to open a file test.txt this file only has one sentence, but it is all in one line only. My job is to separate each word and display all the words that are misspelled.
I've tried using a BufferReader and FileReader, but it just prints out the name of the file. I want it to see the first line and essentially put all the words in an array. If anyone can explain how exactly I should be using BufferReader or FileReader would be great.
This is test.txt:
The warst drought in the United States in neearly a century is expected to drive up the price of milk, beef and pork next yeer, the government said Wednesdaay, as consumers bear some of the bruntt of the sweltering heat that is drivng up the cost of feed corrn.
Note: This appears as one single line in the editor.
This is what I tried:
FileReader fr = new FileReader("test.txt");
BufferReader br = new BufferReader(fr);
StringBuilder sb = new StringBuilder();
String s;
while((s = br.readLine()) != null){
sb.append(s);
sb.toString();
}
Thanks for your help.
for (String line : Files.readAllLines(Paths.get("filepath.txt"))) {
// ...
}
Java: How to read a text file
Related
I have a file in following format:
Name: John
Text: Hello
--empty line-- Buffered Reader is reading this.
Name: Adam
Text: Hi
--empty line-- Buffered Reader is skipping this line.
I tried multiple ways to read the last empty line but its not working. Any suggestions?
I have a program which validates that the message is in correct format or not.
For the correct format there should be three lines first with name followed by text and empty line.
As the last empty line is not read by the BufferedReader, my program always says that the message is in wrong format.
Sample Code I am using:
File file = new File(absolutePath);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
process(line);
}
The code is working the way it is supposed to. The last (empty) line is the end of file (EOF). A valid line is terminated by a carriage return and line feed. Line #3 is read because of this. I included an image of your file showing the text and symbols (used Notepad++ for this)
If I add another blank line at the end, notice how the previous blank line is now terminated.
I modified your code slightly to run this scenario
public static void main (String[] args) throws IOException {
File file = new File("emptyline.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
int linenum = 1;
while ( (line = br.readLine()) != null) {
System.out.println("Line " + (linenum++) + ": " + line);
}
br.close();
}
When I run the code with two blank lines at the end, this is the result:
Line 1: Name: John
Line 2: Text: Hello
Line 3:
Line 4: Name: Adam
Line 5: Text: Hi
Line 6:
If you have software that validates this file based on data being structured this way, I am not sure what to say. That seems a bad way to validate a file. There are more effective ways to do this, like using checksum. Maybe if you try with two empty lines at the end, the validator will accept it as a correct format.
I am reading text from a file and I have been having trouble trying to read List 1 and List 2 into 2 different String . The * indicates where the first list ends. I have tried using arrays but the array only stores the last * symbol.
List 1
Name: Greg
Hobby 1: Swimming
Hobby 2: Football
*
List 2
Name: Bob
Hobby 1: Skydiving
*
Here's what I tried so far:
String s = "";
try{
Scanner scanner = new Scanner(new File("file.txt"));
while(scanner.hasnextLine()){
s = scanner.nextLine();
}
}catch(Exception e){
e.printStackTrace}
String [] array = s.split("*");
String x = array[0];
String y = array[1];
Your code has multiple issues like #Henry said that your string contains only the last line of the file and also you misunderstood the split() because it takes a RegularExpression as a parameter.
I would recommend you to use the following example because it works and is a lot faster than your approach.
Kick-Off example:
// create a buffered reader that reads from the file
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt")));
// create a new array to save the lists
ArrayList<String> lists = new ArrayList<>();
String list = ""; // initialize new empty list
String line; // initialize line variable
// read all lines until one becomes null (the end of the file)
while ((line = reader.readLine()) != null) {
// checks if the line only contains one *
if (line.matches("\\s*\\*\\s*")) {
// add the list to the array of lists
lists.add(list);
} else {
// add the current line to the list
list += line + "\r\n"; // add the line to the list plus a new line
}
}
Explanation
I'm going to explain special lines that are hard to understand again.
Looking at the first line:
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt")));
This line creates a BufferedReader that is nearly the same like a Scanner but it's a lot faster and hasn't as much methods as a Scanner. For this usage the BufferedReader is more than enough.
Then it takes an InputStreamReader as a parameter in the constructor. This is only to convert the following FileInputStream to a Reader.
Why should one do that? That's because an InputStream ≠ Reader. An InputStream returns the raw values and a Reader converts it to human readable characters. See the difference between InputStream and Reader.
Looking at the next line:
ArrayList<String> lists = new ArrayList<>();
Creates a variable array that has methods like add() and get(index). See the difference of arrays and lists.
And the last one:
list += line + "\r\n";
This line adds the line to the current list and adds a new line to it.
"\r\n" Are special characters. \r ends the current line and \n creates a new line.
You could also only use \n but adding \r in front of it is better because this supports more Os's like Linux can have problems with it when \r misses.
Related
Using BufferedReader to read Text File
I have a txt file with three rows of integers, after adding them to a List I'm finding a strange char at the beginning of the first index. I used an InputStream, BufferedReader and StringBuilder to read from the file. I tried to debug using println() statements at several places but I still can't figure out where that char came from.
File selectedFile = fileChooser.getSelectedFile();
inputStream = new FileInputStream(selectedFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
items.add(line);
}
When I try to copy the output from printing out List items to this post somehow the char I'm talking about does not show, so I'll post a screenshot instead:
http://imgur.com/gjaF3no
http://imgur.com/JHAH6mV
The first is of the entire list, and the second should show the char I'm talking more clearly, it looks like a dot before "3". Any help would be appreciated, Thank you.
You can try removing all control characters (strange characters) by doing the following:
strangeString.replaceAll("\\p{Cntrl}", "");
Reference: Java - removing strange characters from a String
Thank you all for the help. The problem was actually in the original txt file like #coder
I'm trying to write a Java application that reads a text file. Suppose I have a text file beg.txt which contains text:
I am a beginner
When the user enters word number 4, the program has to print word 'beginner'.
How can I do this in Java, please?
First give a try before asking this.
Just for your help. Try following steps, this is not the only way.
Read your file
Split string to a string array using space
Print array[your choice - 1]
BufferedReader br = null;
String[] str;
try {
String sCurrentLine;
StringBuilder sb = new StringBuilder();
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine);
}
str = sb.toString.split(" ");
} catch (IOException e) {
e.printStackTrace();
}
if user enters 4 then you can use array 'str' like this :
String result = str[userEnteredValue - 1];
Note: the above code will work only when the file will contain space delimitted characters.
File read=new File("D:\\Test.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(read),Charset.forName("UTF-8")));
String news = reader.readLine();
String[] records = news.split(" ");
if your input is 4
and get records[4]
Well, the basic process will be something like the following:
Load the text file
Get user input
Process text file with parameters from user
Step 1 will depend on which version of Java you're using. If Java 7, I'd look at nio2. Java 6 has other options. Or you could you Guava or Apache Commons. Since the processing required is minimal, I would store the output of this step as a simple String.
Getting the user input can be done in a number of ways, but one option is to use a Scanner.
Finally, processing the file can be done by using String.split() with a simple regex and then picking the correct element from the resulting array.
I am writing a small java app which will scan a text file for any instances of particular word and need to have a feature whereby it can report that an instance of the word was found to be the 14th word in the file, on the third line, for example.
For this i tried to use the following code which i thought would check to see whether or not the input was a newline (\n) character and then incerement a line variable that i created:
FileInputStream fileStream = new FileInputStream("src/file.txt");
DataInputStream dataStream = new DataInputStream(fileStream);
BufferedReader buffRead = new BufferedReader(new InputStreamReader(dataStream));
String strLine;
String Sysnewline = System.getProperty("line.separator");
CharSequence newLines = Sysnewline;
int lines = 1;
while ((strLine = buffRead.readLine()) != null)
{
if(strLine.contains(newLines))
{
System.out.println("Line Found");
lines++;
}
}
System.out.println("Total Number Of Lines In File: " + lines);
This does not work for, it simply display 0 at the end of this file. I know the data is being placed into strLine during the while loop as if i change the code slightly to output the line, it is successfully getting each line from the file.
Would anyone happen to know the reason why the above code does not work?
Read the javadocs for readLine.
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
readLine() strips newlines. Just increment every iteration of the loop. Also, you're overcomplicating your file reading code. Just do new BufferedReader(new FileReader("src/file.txt"))