why doesn´t if (txtLine == null) { break; };work? or maybe the correct answer is why does it still set the string txtLine to null (literally). The way I understand it, it should break the moment the string is null? I don´t want it to set the string to "null". but stop when there are no more lines in the *.txt file
try{
BufferedReader txtReader = new BufferedReader (new FileReader ("test.txt"));
while (true) {
// Reads one line.
println(txtLine);
if(txtLine == null){
break;
};
txtLine = txtReader.readLine();
nLines(txtLine);
}
txtReader.close();
} catch (IOException ex) {
throw new ErrorException(ex);
}
the txtFile variable is defined as an IVAR
private int nChars = 0;
private String txtLine = new String();
private ArrayList <String> array = new ArrayList <String>();
I think the ordering of when you break and when you change the value of txtLine to be the next line read from the file is backwards, your code should look something like:
try{
BufferedReader txtReader = new BufferedReader (new FileReader ("test.txt"));
while (true) {
// Reads one line.
println(txtLine);
txtLine = txtReader.readLine();
// check after we read the value of txtLine
if(txtLine == null){
break;
}
nLines(txtLine);
}
txtReader.close();
} catch (IOException ex) {
throw new ErrorException(ex);
}
But this is a much more concise (and I think, clearer) form:
try{
BufferedReader txtReader = new BufferedReader (new FileReader ("test.txt"));
while ((txtLine = txtReader.readLine()) != null) {
// Reads one line.
println(txtLine);
nLines(txtLine);
}
txtReader.close();
} catch (IOException ex) {
throw new ErrorException(ex);
}
Where while ((txtLine = txtReader.readLine()) != null) sets txtLine to the next line, and then checks that txtLine is not null before continuing.
Related
So I have this method here that should return the amount of lines in a csv file. Pretty simple right? Thing is instead of returning the amount of lines in the csv file(in this case 15) it returns 66. I honestly have know Idea why this would happen. I checked the csv file and verified that it is indeed 15 lines long with no empty lines. Also does anyone know why my Jpanes wont display without those three lines commented lines, my ide says the variables aren't in use anywhere.
public static int getLineCount(){
int line=0;
try {
Scanner inputStream = new Scanner(file);
while (inputStream.hasNext()) {
String data =inputStream.next();//this line is useless but the program doesn't display with out it
String[] values = data.split(",");//this line is useless but the program doesn't display with out it
i++;//this line is useless but the program doesn't display with out it
line++;
}
}catch(FileNotFoundException e){
e.printStackTrace();
}
return line;
}
Use BufferedReader instead of Scanner:
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
while(reader.readLine() != null){
line++;
}
public static int getLineCount(){
String csvFilePath = "C:\\Users\\uzochi\\desktop\\txt.csv";
String line = "";
int numberOfLines=0;
try {
BufferedReader br = new BufferedReader(new FileReader(csvFilePath));
while (( line = br.readLine()) != null) {
numberOfLines++;
}
}catch(FileNotFoundException e){
//
}catch (IOException ex) {
//
}
return numberOfLines;
}
I am trying to replace a string from a js file which have content like this
........
minimumSupportedVersion: '1.1.0',
........
now 'm trying to replace the 1.1.0 with 1.1.1. My code is searching the text but not replacing. Can anyone help me with this. Thanks in advance.
public class replacestring {
public static void main(String[] args)throws Exception
{
try{
FileReader fr = new FileReader("G:/backup/default0/default.js");
BufferedReader br = new BufferedReader(fr);
String line;
while((line=br.readLine()) != null) {
if(line.contains("1.1.0"))
{
System.out.println("searched");
line.replace("1.1.0","1.1.1");
System.out.println("String replaced");
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
First, make sure you are assigning the result of the replace to something, otherwise it's lost, remember, String is immutable, it can't be changed...
line = line.replace("1.1.0","1.1.1");
Second, you will need to write the changes back to some file. I'd recommend that you create a temporary file, to which you can write each `line and when finished, delete the original file and rename the temporary file back into its place
Something like...
File original = new File("G:/backup/default0/default.js");
File tmp = new File("G:/backup/default0/tmpdefault.js");
boolean replace = false;
try (FileReader fr = new FileReader(original);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(tmp);
BufferedWriter bw = new BufferedWriter(fw)) {
String line = null;
while ((line = br.readLine()) != null) {
if (line.contains("1.1.0")) {
System.out.println("searched");
line = line.replace("1.1.0", "1.1.1");
bw.write(line);
bw.newLine();
System.out.println("String replaced");
}
}
replace = true;
} catch (Exception e) {
e.printStackTrace();
}
// Doing this here because I want the files to be closed!
if (replace) {
if (original.delete()) {
if (tmp.renameTo(original)) {
System.out.println("File was updated successfully");
} else {
System.err.println("Failed to rename " + tmp + " to " + original);
}
} else {
System.err.println("Failed to delete " + original);
}
}
for example.
You may also like to take a look at The try-with-resources Statement and make sure you are managing your resources properly
If you're working with Java 7 or above, use the new File I/O API (aka NIO) as
// Get the file path
Path jsFile = Paths.get("C:\\Users\\UserName\\Desktop\\file.js");
// Read all the contents
byte[] content = Files.readAllBytes(jsFile);
// Create a buffer
StringBuilder buffer = new StringBuilder(
new String(content, StandardCharsets.UTF_8)
);
// Search for version code
int pos = buffer.indexOf("1.1.0");
if (pos != -1) {
// Replace if found
buffer.replace(pos, pos + 5, "1.1.1");
// Overwrite with new contents
Files.write(jsFile,
buffer.toString().getBytes(StandardCharsets.UTF_8),
StandardOpenOption.TRUNCATE_EXISTING);
}
I'm assuming your script file size doesn't cross into MBs; use buffered I/O classes otherwise.
I am somewhat new to java and was hoping that someone could help me. I have looked everywhere, but cannot seem to finder a solution.
I'm trying to save the result of a method into a file using bufferedwriter. The bufferedwriter itself works as it is saving some other strings, but when it comes to this function is just displays 'null'. Is is because the result of this method returns more than one string? How do I resolve this?
My code is as following:
Bufferedwriter code:
public static boolean saveStringToFile (String fileName, String saveString)
{
boolean saved = false;
BufferedWriter bw = null;
try
{
bw = new BufferedWriter(new FileWriter(fileName));
try
{
bw.write(saveString);
saved = true;
}
finally
{
bw.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
return saved;
}
The function itself:
public static void getNetDetails()
{
try {
Process net = Runtime.getRuntime().exec("lsof -i -n -P");
BufferedReader netInput = new BufferedReader(
new InputStreamReader(net.getInputStream()));
while ((netDetails = netInput.readLine()) !=null)
{
System.out.println(netDetails);
System.out.println("\n");
}
}
catch(IOException e) {
System.out.println("exception happened - here are the details: ");
e.printStackTrace();
}
}
Saving function to file using bufferedwriter
public static void generateNetReport()
{
saveStringToFile("Net.txt","here is the thing.." + "\n" + netDetails );
}
can someone please help with how I can save netDetails onto a file without it just displaying null??
(Edited.)
This is the problem, in getNetDetails():
while ((netDetails = netInput.readLine()) !=null)
In other words, the method will always leave netDetails as null, unless there's an exception.
It would be better if getNetDetails() returned a string instead of setting a variable, and assuming it's meant to return the final line of the file, it should be something like:
String line = null;
String nextLine;
while ((nextLine = netInput.readLine()) != null) {
line = nextLine;
}
return line;
You should also close the InputStreamReader in a finally block, and almost certainly not swallow the exception.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to create a Java String from the contents of a file
Is it possible to process a multi-lined text file and return its contents as a string?
If this is possible, please show me how.
If you need more information, I'm playing around with I/O. I want to open a text file, process its contents, return that as a String and set the contents of a textarea to that string.
Kind of like a text editor.
Use apache-commons FileUtils's readFileToString
Check the java tutorial here -
http://download.oracle.com/javase/tutorial/essential/io/file.html
Path file = ...;
InputStream in = null;
StringBuffer cBuf = new StringBuffer();
try {
in = file.newInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
cBuf.append("\n");
cBuf.append(line);
}
} catch (IOException x) {
System.err.println(x);
} finally {
if (in != null) in.close();
}
// cBuf.toString() will contain the entire file contents
return cBuf.toString();
Something along the lines of
String result = "";
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
// Here's where you get the lines from your file
result += dis.readLine() + "\n";
}
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
String data = "";
try {
BufferedReader in = new BufferedReader(new FileReader(new File("some_file.txt")));
StringBuilder string = new StringBuilder();
for (String line = ""; line = in.readLine(); line != null)
string.append(line).append("\n");
in.close();
data = line.toString();
}
catch (IOException ioe) {
System.err.println("Oops: " + ioe.getMessage());
}
Just remember to import java.io.* first.
This will replace all newlines in the file with \n, because I don't think there is any way to get the separator used in the file.
I just wanted to know if there is any restriction on the number of lines readLine method can read from a file in java.Any help will be grately appreciated.This is what I am talking about:
FileReader fr1=new FileReader("/homes/output_train_2000.txt");
BufferedReader br1=new BufferedReader(fr1);
while((line1=br1.readLine())!=null){ }
Thanks.
When buffered reader is used, the entire file is never read into memory, so it should be able to handle files of any size that your operating system supports for.
It can read any number of lines .
Are you trying to restrict the number of lines read? If so then you can easily add some code to do that:
FileReader fr1=new FileReader("/homes/output_train_2000.txt");
BufferedReader br1=new BufferedReader(fr1);
int numLinesRead = 0;
int maxLines = 1000;
while((numLinesRead < maxLines) && (line1=br1.readLine())!=null){
numLinesRead++;
// other stuff
}
No restriction that I know of. Here's a better way of doing it:
BufferedReader reader = null;
try {
reader = new BufferedReader( new FileReader( "/homes/output_train_2000.txt") );
String line = null;
do {
line = reader.readLine();
if( line != null ) {
// Do something
}
} while( line != null );
} catch (Exception e) {
e.printStackTrace();
} finally {
if( reader != null )
try {
reader.close();
} catch (IOException e) {
}