In Java I'm using the Scanner to read from a text file,
for example (cat, dog, mouse).
When I use the System.out.println() the output appears like cat, dog, mouse
I want the list to look like this
cat
dog
mouse
any help code below
Scanner scan = null;
Scanner scan2 = null;
boolean same = true;
try {
scan = new Scanner(new
File("//home//mearts//keywords.txt"));
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
List<String> firstLines = new ArrayList<String>();
while (scan.hasNextLine()) {
firstLines.add(scan.nextLine());
System.out.println(firstLines);
}
You are reading the file line by line, instead of taking the delimiters into consideration:
try (Scanner scan =
new Scanner("//home//mearts//keywords.txt").useDelimiter(", ")) {
while (scan.hasNext()) {
System.out.println(scan.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace(); // Or something more useful
}
Try something like:
firstLines.forEach(System.out::println);
By the way, as you are only reading lines, you may also want to have a look at java.nio.file.Files:
Path keywordsFilepath = Paths.get(/* your path */...);
Files.lines(keywordsFilepath)
.forEach(System.out::println);
Related
I'm trying to read multiple lines from a text file before reaching a certain string, "***", which I would then like to print out. How do I do this?
Code:
public void loadRandomClass(String filename) {
try {
Scanner scan = new Scanner(new File(filename));
while((scan.hasNextLine()) && !(scan.nextLine().equals("***"))) {
}
scan.close();
} catch (FileNotFoundException e) {
System.out.println("Something went wrong");
e.printStackTrace();
}
}
I have tried some stuff, but it keeps skipping every 2nd line, starting from the 1st and it doesn't stop before "***".
The problem is that scan.nextLine() reads the line and deletes it from the buffer i suppose. Try this:
while(scan.hasNextLine()) {
String next = scan.nextLine();
if(next.contains("***") break;
System.out.println(next);
}
demo.txt :
FD1,true,102400,4000,0.01,103,83.25
FD0,false,102400,4000,0.01,103,83.25
I want to access each line 1st then from each line i want to access each element and pass this as parameter to a function createFogDevice to perform some action.
like createFogDevice(FD1,true,1024,4000,0.01,103,83.25)
Can anybody help how we can write code for this ?
Scanner scanner = new Scanner(new File());
while(scanner.hasNextLine()) {
String currentLine = scanner.nextLine();
String[] dataPoints = currentLine.split(",");
String a = dataPoints[0];
boolean b = Boolean.parseBoolean(dataPoints[1]);
// ....
createFogDevice(a,b,c/*...*/);
}
Try This :-
try (Stream<String> stream = Files.lines(Paths.get("demo.txt"))) {
stream.forEach(ob->createFogDevice(ob.split(",")));
} catch (IOException e) {
e.printStackTrace();
}
Also you can modify createFogDevice() method to pass Array of String as argument :-
private static void createFogDevice(String[] inputParams) {
// your code goes here
}
I am trying to replace ? with - in my text document but just the ArrayList<String> is being written in the new file without all lines of the old one. How can I fix that?
File file = new File("D:\\hl_sv\\L09MF.txt");
ArrayList<String> lns = new ArrayList<String>();
Scanner scanner;
try {
scanner = new Scanner(file);
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if (line.contains("?")) {
line = line.replace("?", "-");
lns.add(line);
// System.out.println("I found it on line " + lineNum);
}
}
lines.clear();
lines = lns;
System.out.println("Test: " + lines);
FileWriter writer;
try {
writer = new FileWriter("D:\\hl_sv\\L09MF2.txt");
for (String str : lines) {
writer.write(str);
}
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I don't understand why you're storing the lines in a List to begin with. I would perform the transform and print while I read. You don't need to test for the presence of the ? (replace won't alter anything if it isn't present). And, I would also use a try-with-resources. Something like
File file = new File("D:\\hl_sv\\L09MF.txt");
try (PrintWriter writer = new PrintWriter("D:\\hl_sv\\L09MF2.txt");
Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
writer.println(line.replace('?', '-'));
}
} catch (Exception e) {
e.printStackTrace();
}
Examine this code:
if (line.contains("?")) {
line = line.replace("?", "-");
lns.add(line);
}
You are only adding the current line (with the replacement) if it had a ? in it, ignoring other lines. Restructure it to always add the existing line.
if (line.contains("?")) {
line = line.replace("?", "-");
}
lns.add(line);
Additionally, the part
if (line.contains("?"))
scans line to look for a ?, and then the code
line.replace("?", "-");
does the same thing, but this time also replacing any ? with -. You may as well scan line just once:
lns.add(line.replace("?", "-"));
Note that creating an ArrayList just to hold the new lines wastes a fair amount of memory if the file is large. A better pattern would be to write each line, modified if necessary, right after you read in the corresponding line.
Within your while loop you have an if statement checking the line which adds the altered line to the array. You also need to add the unaltered lines to the array.
This should fix your issue:
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if (line.contains("?")) {
line = line.replace("?", "-");
lns.add(line);
// System.out.println("I found it on line " + lineNum);
}
else{
lns.add(line);
}
Previously, you were only adding the line to your ArrayList if it contained a "?" character. You need to add the line to the ArrayList whether or not it contains "?"
I would use a different approach if I'm trying to work on the functionality you want to implement, please check this approach and tell me if this helps you :)
public void saveReplacedFile() {
//1. Given a file in your system
File file = new File("D:\\hl_sv\\L09MF.txt");
try {
//2. I will read it, not necessarily with Scanner, but use a BufferedReader instead
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
//3. Define a variable that will hold the value of each line
String line = null;
//and also the information of your file
StringBuilder contentHolder = new StringBuilder();
//why not get your line separator based on your O.S?
String lineSeparator = System.getProperty("line.separator");
//4. Check your file line by line
while ((line = bufferedReader.readLine()) != null) {
contentHolder.append(line);
contentHolder.append(lineSeparator);
}
//5. By this point, your contentHolder will contain all the data of your text
//But it is still a StringBuilder type object, why not convert it to a String?
String contentAsString = contentHolder.toString();
//6. Now we can replace your "?" with "-"
String replacedString = contentAsString.replace("?", "-");
//7. Now, let's save it in a new file using BufferedWriter :)
File fileToBeSaved = new File("D:\\hl_sv\\L09MF2.txt");
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileToBeSaved));
bufferedWriter.write(replacedString);
//Done :)
} catch (FileNotFoundException e) {
// Exception thrown if the file does not exist in your system
e.printStackTrace();
} catch (IOException e) {
// Exception thrown due to an issue with IO
e.printStackTrace();
}
}
Hope this is helpful. Happy coding :)
If you can use Java 8 then your code can be simplified to
try (PrintStream ps = new PrintStream("D:\\hl_sv\\L09MF2.txt");
Stream<String> stream = Files.lines(Paths.get("D:\\hl_sv\\L09MF.txt"))) {
stream.map(line -> line.replace('?', '-')).forEach(ps::println);
} catch (IOException e) {
e.printStackTrace();
}
I am having some very wierd issues while attempting to read a file.
Its only a few lines of simple code, but for some reason its thinking that my file has 8 lines of wierd rumbo jumbo text, while it has 2 lines and 4 letters in each line.
Code (Executed once, it's reading the correct file)
Scanner scanner = null;
ArrayList<String> lines = new ArrayList<String>();
try {
scanner = new Scanner(getClass().getResourceAsStream("/level.txt"));
} catch (Exception ex) {
ex.printStackTrace();
}
while (scanner.hasNext()) {
lines.add(scanner.nextLine());
}
Main.main.log(lines.size() + " size");
File (level.txt, with no spaces)
sssas
sssas
Output:
8 Size
Its super weird since it's only a few lines and a simple file.
Any help, suggestions or error's made? There are no stacktraces!
Thanks,
Jake
Java 7 one-liner to read a file to a list:
List<String> lines = Files.readAllLines(
Paths.get(getClass().getResource("/level.txt").toURI()),
StandardCharsets.UTF_8
);
The first issue to consider is as #Sotirios Delimanolis says, you may read from a wrong txt file.
The second issue is that if you are perfectly sure about reading from the correct .txt file, the solution is to read with reading scanner.hasNextLine() while appending to the "lines" variable.
I think the problem occurs when you read with "hasNext()" which reads token by token, and go into next step with "scanner.nextLine()" which goes to the next line.
For example you may use the following;
Scanner scanner = null;
ArrayList<String> lines = new ArrayList<String>();
try {
scanner = new Scanner(getClass().getResourceAsStream("/level.txt"));
} catch (Exception ex) {
ex.printStackTrace();
}
while (scanner.hasNextLine()) { /* difference is here */
lines.add(scanner.nextLine());
}
Main.main.log(lines.size() + " size");
EDIT:
You can use the following code and modify it however you want.
I think the problem is also occurs when you are reading the File. To read the file you can use new File() constructor instead of your choice. See below:
Scanner scanner = null;
ArrayList<String> lines = new ArrayList<String>();
try {
scanner = new Scanner(new File("level.txt")); /* difference is here */
} catch (Exception ex) {
ex.printStackTrace();
}
while (scanner.hasNextLine()) { /* difference is here */
lines.add(scanner.nextLine());
}
System.out.println(lines.size()); // gives output 2.
I would suggest to go on different kind of method which is more correct to do..
public static void main(String[] args) {
BufferedReader br = null;
ArrayList<String> lines = new ArrayList<String>();
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
lines.add(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
This will do the trick perfectly.. hope that helps
EDIT:
If you would like to read file from classpath of the project you can use the following:
InputStream in = this.getClass().getClassLoader().getResourceAsStream("SomeTextFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
Somethink like that will be fine.. I am not saying you cannot do it with scanner.. IMHO I think this is better.. But it is a matter of choice and not big architecture problem.. Consideration is yours :)
I am new to Java. I am trying to added few words from a text file to my existing text based word list. I have the below code doing
Add words from an file to existing list
Sort the list of words
Save the words to a text file
"wordList" is an arraylist with existing words.
private void updateDictionaryFile(String filepath) {
String textCurrentLine = "";
BufferedReader dictionaryFile = null;
try {
Scanner fileScanner = new Scanner(new File(filepath));
while(fileScanner.hasNextLine()){
System.out.println("fileScanner.hasNextLine() "+ fileScanner.hasNextLine());
textCurrentLine = fileScanner.nextLine();
if(textCurrentLine.length() > 0)
if (!wordList.contains(textCurrentLine)) {
wordList.add(textCurrentLine);
}
}
Collections.sort(wordList);
String newFile = filepath.replace(".txt", "_new.txt");
PrintWriter pw = new PrintWriter(new FileOutputStream(newFile));
for (int i = 0; i < wordList.size(); i++) {
pw.println(wordList.get(i).toString());
}
pw.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (dictionaryFile != null) {
dictionaryFile.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Word listed in new file is not sorted. Am I missing something in between?
Below is the output
A
Achieve
Although
Anything
Ask
Avoid
Badly
Bluma
But
Find
Forget
Goal
Goals
How
In
It
Just
Keep
Know
NOT
Often
Once
One
Psychologists
Reasoning
Reject
Remember
Research
Russian
Shifting
Sidestep
So
Sometimes
Start
Stop
The
This
Those
Under
Visualise
Visualising
We
What
When
With
You
Zeigarnik
a
aa
aah
aahed
aahing
aahs
aal
aalii
aaliis
aals
aardvark
aardwolf
aargh
aarrgh
aarrghh
aas
Collections.sort(wordList); will work perfectly. if need to ignore the case then use below code.
Collections.sort(wordList,String.CASE_INSENSITIVE_ORDER);