I am trying to read contents of a jar file. Below code i have written for this. I have placed the jar file under lib directory(\practice\lib\abc.jar).
final InputStream is = JarReader.class.getResourceAsStream("/abc.jar");
BufferedReader input = new BufferedReader(new InputStreamReader(is));
Scanner scan = new Scanner(input);
while (scan.hasNext()) {
String s = scan.next();
System.out.println(s);
}
scan.close();
every time inputStream coming as null. Below post i have used for my reference
getResourceAsStream returns null
How to read a file from jar in Java?
String s = scan.next();
This line in your code will read the file line after line. It's up to you on how to use those lines. You might want to create a StringBuilder and keep appending those lines. Or store it as plain String or something else if you prefer.
But you already have the file with you (in the form of individual lines).
Related
I have to modify a text file in java.
eg this is the file before modify
line
line
line
line
line
line
and after it should look like:
line
line
this is another
line
line
line
line
So don't write over anything, only add a line between the 2. and 3. line, and the original 3. line will be the new 4. line.
A way is to make a temp file, write every line in it, and where I want to modify I do the modification. Than delet the original, and rename the temp file. Or read the temp file and write it to te original file.
But is there any way to read and modify a file like I want using the same class in java?
thx!
You can read and modify to and from a file in Java at the same time. The problem you have though is that you need to insert data here, in order to do that everything after the new line needs to be shuffled down and then the length of the file extended.
Depending on exactly what and why you are trying to do there are a number of ways to do this, the easiest is probably to scan the file copying it to a new location and inserting the new values as you go. If you need to edit in place though then it's more complicated but essentially you do the same thing: Read X characters to a buffer, overwrite the X characters in the file with the new data, read next X characters. Overwrite the just-read characters from the first buffer. Repeat until EOF.
Think of files on disk as arrays - if you want to insert some items into the middle of an array, you need to shift all of them to make room.
The only safe way is to create a new temp file, copy the old file line by line and then rename it, just as you suggested. By updating the same file directly on the disk you risk losing the data if anything goes wrong and you would use a lot of memory.
Try this:
public void writeAfterNthLine(String filename, String text, int lineno) throws IOException{
File file = new File(filename);
File temp = File.createTempFile("temp-file-name", ".tmp");
BufferedReader br = new BufferedReader(new FileReader( file ));
PrintWriter pw = new PrintWriter(new FileWriter( temp ));
String line;
int lineCount = 0;
while ((line = br.readLine()) != null) {
pw.println(line);
if(lineCount==lineno){
pw.println(text);
}
lineCount++;
}
br.close();
pw.close();
file.delete();
temp.renameTo(file);
}
The code is not tested, but it should work, you can improve the code with several validations and exception handling
I am trying to read a log file word by word using a scanner and using the code
Scanner scanner = new Scanner(file);
while(scanner.hasNext()){
String word = scanner.next();
}
But the problem is that this stops after it reaches the end of the file but I need to read it as it gets generated
I tried this to solve this using the below code
Scanner scanner = new Scanner(file);
while(true){
while(!scanner.hasNext()){
Thread.sleep(1000);
}
String word = scanner.next();
}
But the code does not seem to work and gets stuck in the while loop even when the log file has more data appended to it.
Can someone point out what i am doing wrong.
I made an small snippet for reading a log file for another system. I used BufferedReader instead of Scanner. Because it will run until the end of file and still reading. Instead of using the Scanner Next.
readLine() Doc:
* #return 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
And My Snippet
BufferedReader br = new BufferedReader(new InputStreamReader(file));
while (true)
{
strLine = br.readLine();
if(strLine!=null)
{
System.out.println(strLine);
}else{
Thread.sleep(100);
}
}
I need to read contents of a file as a server, and then send the read data file, for the client so the client print it out on the Client terminal.
The problem is that I can't find a way or method to read a txt file from the current directory which my java file and txt file are existed.
Please help me.
There are many ways to read text file or file in java. It depend on you to that in which format you need to pass your file content to client side.
Here are some method to reading file in java.
1. Using BufferedReader class
BufferedReader input = new BufferedReader(new FileReader(aFile));
String line = null; //not declared within while loop
while (( line = input.readLine()) != null){
String curLine = line;
//Process line
}
2.Using Apache Common IOUtils with the class IOUtils.toString() method.
FileInputStream inputStream = new FileInputStream("FILEPATH/FILENAME");
try {
String everything = IOUtils.toString(inputStream);
} finally {
inputStream.close();
}
3.Using the Scanner class in Java and the FileReader
Scanner in = new Scanner(new FileReader("FILENAME/FILEPATH"));
while (scanner.hasNextLine()){
//process each line in some way
String line = scanner.nextLine();
}
Scanner has several methods for reading in strings, numbers, etc...
4.In JAVA 7 this is the best way to simply read a textfile
new String(Files.readAllBytes(...))
or Files.readAllLines(...)
Path path = Paths.get("FILENAME");
List<String> allLines = Files.readAllLines(path, ENCODING);
Please refer this link for more onfomation.
You can use BufferedReader to read from a txt file.
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
here fileName is a string that contain your absolute file name.
eg : fileName = "C:\temp\test.txt";
You can read file by using BufferedReader.
File file=new File("filepath");
BufferedReader br=new BufferedReader(new FileReader(file)); //Here you create an object of bufferedreader which file read through filereader
String data=br.readLine();
while(data!=null)
{
System.out.println(data); // Writing in the console
data=br.readLine();
}
This will taking input from file and giving output to console.If you want it write in other file then use BufferedWriter.
File out=new File("outputfilepath");
BufferedWriter bw=new BufferedWriter(new FileWriter(out));
simply us bw.write() instead of System.out.println();.
I have to modify a text file in java.
eg this is the file before modify
line
line
line
line
line
line
and after it should look like:
line
line
this is another
line
line
line
line
So don't write over anything, only add a line between the 2. and 3. line, and the original 3. line will be the new 4. line.
A way is to make a temp file, write every line in it, and where I want to modify I do the modification. Than delet the original, and rename the temp file. Or read the temp file and write it to te original file.
But is there any way to read and modify a file like I want using the same class in java?
thx!
You can read and modify to and from a file in Java at the same time. The problem you have though is that you need to insert data here, in order to do that everything after the new line needs to be shuffled down and then the length of the file extended.
Depending on exactly what and why you are trying to do there are a number of ways to do this, the easiest is probably to scan the file copying it to a new location and inserting the new values as you go. If you need to edit in place though then it's more complicated but essentially you do the same thing: Read X characters to a buffer, overwrite the X characters in the file with the new data, read next X characters. Overwrite the just-read characters from the first buffer. Repeat until EOF.
Think of files on disk as arrays - if you want to insert some items into the middle of an array, you need to shift all of them to make room.
The only safe way is to create a new temp file, copy the old file line by line and then rename it, just as you suggested. By updating the same file directly on the disk you risk losing the data if anything goes wrong and you would use a lot of memory.
Try this:
public void writeAfterNthLine(String filename, String text, int lineno) throws IOException{
File file = new File(filename);
File temp = File.createTempFile("temp-file-name", ".tmp");
BufferedReader br = new BufferedReader(new FileReader( file ));
PrintWriter pw = new PrintWriter(new FileWriter( temp ));
String line;
int lineCount = 0;
while ((line = br.readLine()) != null) {
pw.println(line);
if(lineCount==lineno){
pw.println(text);
}
lineCount++;
}
br.close();
pw.close();
file.delete();
temp.renameTo(file);
}
The code is not tested, but it should work, you can improve the code with several validations and exception handling
I want to open a file and then read it line by line. In some lines I want to append a string to exactly this line. Is this possible?
I have a code for opening the file and reading it like the following:
File file = new File("MyFile.txt");
BufferedReader bufRdr = new BufferedReader(new FileReader(file));
String line = null;
try {
while((line = bufRdr.readLine()) != null)
{
// read line by line and append some string to the line
}
} catch (IOException e) {
// ...
}
but how can I append a string to the current line and write this to the file?
As you are reading file line by line. append your text to line and write it to other file. Say for example file with different name and later you can rename the file.
Just like
try {
while((line = bufRdr.readLine()) != null)
{
// read line by line and append some string to the line
//pseudo code
newline = line + "yourtext";
outputstreamtootherfile.write(newline);
}
}
I think there is no way you can read and write to same file concurrently, as it holds read/write locks.
Thanks
readLines read lines to List<String> and change some String (line) if you need it
create new temp file
write lines (or line by line) to it by append
remove old file
rename
Create new file and keep on writing to this file (as you read other file line by line) with the modification you want. Then delete the existing one and give the newly created file the name of deleted file.This is how i would approach it.
Here is the link which confirms this approach alongwith other alternatives.
Modify a .txt file in Java