When writing a program in Java, and you want to read a file, is there a way the USER can have the program completely ignore certain lines or characters by making the certain file's line or character into more of a 'comment'? Just as a programmer can use '//' or '/* */' while programming.
You can skip the lines that start with a certain pattern (e.g. '//' or '#').
There's an example on how to read a file in Java line by line here: http://www.roseindia.net/Java/beginners/java-read-file-line-by-line.shtml
You can change the while-loop like this:
while ((strLine = br.readLine()) != null) {
if (!strLine.startWith("#"))
System.out.println (strLine);
}
In this example lines starting with '#' will not get printed.
If it is a properties file format and you are using Properties to read it, you can use the pound character. Otherwise, no, you will need to implement something yourself.
my.prop1=val1
#some comment
my.prop2=val2
Sure. If program uses code like this to read lines from the file:
BufferedReader reader =
new BufferedReader (
new InputStreamReader (new FileInputStream (inputFile)));
String line;
while ((line = reader.readLine ()) != null)
{
if (line.startWith ("#") || line.trim ().isEmpty ())
continue; // Ignore the line
// Process the line
}
User can mark some lines as comments by prefixing them with pound ('#') character.
this depends on what you want to accomplish
if you simply want to transform the new file, then you can use BufferedReader reader to read the file line by line and then check each line to see if it meet some criteria,
and take the necessary action
like if (line.startWith ("#") || line.trim ().isEmpty ()) otherwise it will be better to use standard libraries to perform operations on your file, such as compressing the file, changing the file to a different format etc
Related
I am trying to make a smaller version of Pwned Passwords (https://haveibeenpwned.com/Passwords) for my Ap comp sci project. Everything is goo besides 2 things:
(Issue 1) (image of my code to show better)
I have this below my jForm source code which declares each button/etc and what they do. I get this error though: "Illegal static declaration in inner class PassCheck.check. I do not now how to resolve this issue.
The second issue is using FileReader and Buffered Reader. I want the program to read the text inputted from the jForm and compare it to a file which has a list of commonly used passwords. How can I do this? Here is my code so far of just practicing with FR and BR:
import java.io.*;
public class MainFileReader {
public static void main(String[] args) throws Exception{
String refpass, input;
input = "1234";
FileReader fr = new FileReader("C:\\Users\\tcoley\\Downloads\\207pass.txt");
BufferedReader br = new BufferedReader(fr);
while((input = br.readLine()) != null){
refpass = br.readLine();
And I stopped here. I apologize as Java is not my strong suit but any help is much appreciated!
For your issue #2 - input is the string variable that is to be used hold the password you want to find in the file yet you eliminate its contents when you apply it to reading a line: (input = br.readLine()). It will now hold the currently read file line (this is no good). You need to use the refPass variable instead, for example: (refPass = br.readLine()).
You only need to use br.readLine() once in your loop. What your code is effectively doing right now (if it runs) is reading two (2) file lines on each iteration of the while loop. It could potentially fall into an Exception since there is no protection for null in the second read. Again no good.
Once you've read a file line, ensure it actually contains something. A lot of times a file will have a blank line in it that can throw a monkey wrench into things if it's not handled. To check for this you can do something like what is shown below after a line is read into refPass:
while((refPass = br.readLine()) != null) {
// remove leading & trailing whitespaces (if any).
refPass = refPass.trim();
// Skip past blank lines in file (if any).
if (refPass.isEmpty()) {
continue;
}
// .... rest of code ...
}
Now to complete your loop block code, you just need to compare the password read in with the password contained within the input variable (ex: "1234"). To do this, you could have something like this:
if (refPass.equals(input) {
System.out.println("Password Found!")
break; // Break out of the 'while' loop and close file.
}
On a side: Don't use == to compare Strings for content equality, that may not always work as you expect. Use the String#equals() method instead. Give the supplied link a read.
At the end of and outside your while loop, be sure to close the reader, for example: br.close(); so as to release hold on the file and free up resources.
You don't need to use BufferedReader. Buffering is only for inefficient reading and writing (ie doing multiple reads and writes)
Use Path and Files instead
Path p = "C:\\Users\\tcoley\\Downloads\\207pass.txt";
String file = new String(Files.loadAllBytes(p));
What does the file look like? There are a lot of ways to format a file and for simplicities sake, this will just assume it's one word per line:
With the line
refpass = br.readLine();
You are taking in the line from the file
boolean isEqual = refpas.equals(input);
This allows you to assess the line individually.
Remember that '==' is not the way to use String comparisons in Java.
("cat" == "cat") != ("cat".equals("cat"))
I am using Java to run a program and reading the program's text output into a buffered reader. I then want to print out the results by doing this:
while((line=input.readLine()) != null){
System.out.println(line);
}
For some reason, when doing this the readLine() method does not return at all about halfway through the text, and the program waits indefinitely. Yet when running this program from the command line directly, its output is exactly as expected, just 100 lines or so of simple text. What could cause readLine() to not return halfway through reading simple text?
This may happen if nothing has been written to the stream.
You may often encounter the situation in which readLine() hangs is when you invoke a process that is supposed to write errors to stderr. When the process finishes you may try to read all the errors by doing:
BufferedReader brCleanUp = new BufferedReader(new InputStreamReader(stderr));
while ((line = brCleanUp.readLine()) != null) {
//process the error line
}
brCleanUp.close();
But if nothing at all was written to stderr, the above readLine() would hang as you described.
The way to avoid it is to check if there is any point of reading the stream (I don't know if it's a bug or not, but this worked for me:)
boolean available = stderr.available() >= 1;
if (available) {
BufferedReader brCleanUp = new BufferedReader(new InputStreamReader(stderr));
for( ; available && (line = brCleanUp.readLine()) != null;
available = stderr.available() >= 1) {
System.out.println ("[Stderr] " + line);
}
brCleanUp.close();
}
You need to encode the text document into UTF-8 like this, then use Scanner.
// specify file path
String filePath = "C:/path/path/file-location/file.txt";
// make a scanner with the UTF-8 param
Scanner scanner = new Scanner(new File(filePath),"UTF-8");
// loop through text
while (scanner.hasNextLine()){
System.out.println(scanner.nextLine());
}
There are actually a few ways to encode text like this, but the importance lies within the text encoding itself. Once you have the document in the correct format, the objects and classes you chose to read input are at your own discretion.
What could cause readLine() to not return halfway through reading simple text?
If you are reading from a file in a file system, this is possibly due to a problem with the file system; e.g. a remote file server is not responding.
If you are reading from a socket, either the remote server hasn't (yet) written / flushed the data you are trying to read, or a network problem is stopping the data from getting through.
If you are reading from a pipe (e.g. the output of another program), then the other program hasn't written / flushed the data you are trying to read.
(Another cases are reading from a "device file" or a file in the "/proc" file system, or a loopback file system. In these cases, the possible causes are difficult to enumerate.)
I have a text file with various key value pairs separated with a '--'.
Below is the code I have so far
File file = new File("C:\\StateTestFile.txt");
BufferedWriter out = new BufferedWriter(file.getAbsolutePath());
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
if(line.contains("content_style")) {
//Write to the line currently reading and save back to the file
}
}
br.close();
out.close();
What I would like to do is read this text file and replace the value of a specific line with something I specify. So id want to find the 'content_style' line and replace 'posh' with 'dirty'.
How can I do this?
simply use:
line = line.replaceAll("posh", "dirty"); // as strings are immutable in java
This can be done in-place on a single file only if you are sure that the string you are replacing is exactly the same length in bytes as the string that replaces it. Otherwise, you can't add or delete characters in a single file, but you can create a new file.
Open the source file for reading.
Open the destination file for writing.
Read each line in the source file, use replaceAll, and write it to the destination file.
Close both files.
Alternate method that preserves the key-value semantics:
Open the source file for reading.
Open the destination file for writing.
Split each line in the source file into a key and value pair. If the key equals "content_style", write the key and "dirty" to the destination file. Otherwise write the key and value.
Close both files.
Finally, delete the old file and rename the new file on top of the old one. If you're going to be doing key-value manipulations often, and you don't want to write out a new file all the time, it might be worth it to use a database. Look for a JDBC driver for SQLite.
I want to read the last 2 lines in some files, and if the content of second last line matches a specific string, then delete the last line only.
Also, after the above operation, 2 lines of data have to be appended to the end of the modified file. I saw other questions on SO that deal with different parts of my problem, but is there an easy way of doing all of the above with minimal code, preferably in a single function? (I can combine the different functions available at SO but that would be messy...)
I would recommend you to do it "in memory". It's easy to read line by line into a List, check the last lines and update the lines and write it back to the file.
Example:
public static void main(String[] args) throws IOException {
String fileName = "test.txt";
List<String> lines = new ArrayList<String>();
// read the file into lines
BufferedReader r = new BufferedReader(new FileReader(fileName));
String in;
while ((in = r.readLine()) != null)
lines.add(in);
r.close();
// check your condition
String secondFromBottom = lines.get(lines.size() - 2);
if (secondFromBottom.matches("Hello World!")) {
lines.remove(lines.size() - 1);
lines.add("My fixed string");
}
// write it back
PrintWriter w = new PrintWriter(new FileWriter(fileName));
for (String line : lines)
w.println(line);
w.close();
}
Note: No exception handling is done in the example above... you need to handle cases where the file for example doesn't contain two lines and other problems!
If you have really big files and perfomance is an issue the way to go is to use a RandomAccessFile and read backwards looking for the line termination bytes to determine where the last two lines begin. Otherwise use dacwe's approach.
As Gandalf said you can:
take RandomAccessFile,
use method seek(long) to jump forward and read those lines. But you won't know exactly how big the jump should be.
to delete last lines you need the position of begin of last line so before reading each line store their file pointer position (method getFilePointer()). Deleting to that position you use setLength(long).
My example of reading and deleting last lines you have here:
Deleting the last line of a file with Java
Useful can be also:
Quickly read the last line of a text file?
I'm trying to parse a .csv file with OpenCSV in NetBeans 6.0.1. My file contains some Unicode character. When I write it in output the character appears in other form, like (HJ1'-E/;). When when I open this file in Notepad, it looks ok.
The code that I used:
CSVReader reader=new CSVReader(new FileReader("d:\\a.csv"),',','\'',1);
String[] line;
while((line=reader.readNext())!=null){
StringBuilder stb=new StringBuilder(400);
for(int i=0;i<line.length;i++){
stb.append(line[i]);
stb.append(";");
}
System.out.println( stb);
}
First you need to know what encoding your file is in, such as UTF-8 or UTF-16. What's generating this file to start with?
After that, it's relatively straightforward - you need to create a FileInputStream wrapped in an InputStreamReader instead of just a FileReader. (FileReader always uses the default encoding for the system.) Specify the encoding to use when you create the InputStreamReader, and if you've picked the right one, everything should start working.
Note that you don't need to use OpenCSV to check this - you could just read the text of the file yourself and print it all out. I'm not sure I'd trust System.out to be able to handle non-ASCII characters though - you may want to find a different way of examining strings, such as printing out the individual values of characters as integers (preferably in hex) and then comparing them with the charts at unicode.org. On the other hand, you could try the right encoding and see what happens to start with...
EDIT: Okay, so if you're using UTF-8:
CSVReader reader=new CSVReader(
new InputStreamReader(new FileInputStream("d:\\a.csv"), "UTF-8"),
',', '\'', 1);
String[] line;
while ((line = reader.readNext()) != null) {
StringBuilder stb = new StringBuilder(400);
for (int i = 0; i < line.length; i++) {
stb.append(line[i]);
stb.append(";");
}
System.out.println(stb);
}
(I hope you have a try/finally block to close the file in your real code.)