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.
Related
When I am writing text in this txt file, there either is no space between the new string and the old existing string, or there is extra lines, which messes up my other algorithms.
public String writeStudent(String file, String name)
{
String txt = "";
//set through put method
try(FileWriter fw = new FileWriter(file + ".txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println(name + "\r\n");
//save userinput into class1.txt
txt ="added: " + name;
}
catch(IOException e)
{
System.out.println("error");
e.printStackTrace();
// detact error
}
return txt;
}
This is the code I am using to writing in txt, using (name + "\r\n") gives me extra empty lines.
How about use BufferedWriter instead of PrintWriter?
It's my sample code. please try test below code.
import java.io.*;
public class Stackoverflow {
public static void main(String[] args) {
File file = new File("C:\\test.txt");
OutputStream outputStream = null;
Writer writer = null;
BufferedWriter bufferedWriter = null;
try {
outputStream = new FileOutputStream(file);
writer = new OutputStreamWriter(outputStream);
bufferedWriter = new BufferedWriter(writer);
bufferedWriter.write("Hello");
bufferedWriter.write("\r\n");
bufferedWriter.write("\r\n");
bufferedWriter.write("Bye");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bufferedWriter != null) {
try {
bufferedWriter.close();
} catch (Exception ignore) {
}
}
if (writer != null) {
try {
writer.close();
} catch (Exception ignore) {
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception ignore) {
}
}
}
}
}
output
Hello
Bye
The problem is the println function automatically adds new line at end of input string.
out.println(name + "\r\n"); Is effectively the same as out.print(name + "\r\n\r\n");
Lastly you need to think about if new line needs to be before or after your student name.
The solution is to simply use print instead of println and add a new line before the student name
For example.
Given existing text file
John Doe
and you want a new name to be added as
John Doe
Jane Doe
The newline is actually before your name input. Meaning you should use something like out.print("\r\n" + name);
This question already has answers here:
Write a file in UTF-8 using FileWriter (Java)?
(9 answers)
Closed 5 years ago.
Below is my code, it is intended to take two .ckl files, compare the two, add the new items and create a new merged file. The program executes correctly when run in Netbeans however, when executing the .jar the program doesn't appear to be encoding the file in UTF-8. I am rather new to programming and would like to know where or how I might need to be enforcing this encoding to take place?
** I have removed the Swing code and other lines so that only my method is shown, the method that does all of the comparing and merging.
public void mergeFiles(File[] files, File mergedFile) {
ArrayList<String> list = new ArrayList<String>();
FileWriter fstream = null;
BufferedWriter out = null;
try {
fstream = new FileWriter(mergedFile, false);
out = new BufferedWriter(fstream);
} catch (IOException e1) {
e1.printStackTrace();
}
// Going in a different direction. We are using a couple booleans to tell us when we want to copy or not. So at the beginning since we start
// with our source file we set copy to true, we want to copy everything and insert vuln names into our list as we go. After that first file
// we set the boolean to false so that we dont start copying anything from the second file until it is a vuln. We set to true when we see vuln
// and set it to false if we already have that in our list.
// We have a tmpCopy to store away the value of copy when we see a vuln, and reset it to that value when we see an </VULN>
Boolean copy = true;
Boolean tmpCopy = true;
for (File f : files) {
textArea1.append("merging files into: " + mergedFilePathway + "\n");
FileInputStream fis;
try {
fis = new FileInputStream(f);
// BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(mergedFile), "UTF-8"));
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String aLine;
while ((aLine = in.readLine()) != null) {
// Skip the close checklist and we can write it in at the end
if (aLine.trim().equals("</iSTIG>")) {
continue;
}
if (aLine.trim().equals("</STIGS>")) {
continue;
}
if (aLine.trim().equals("</CHECKLIST>")) {
continue;
}
if (aLine.trim().equals("<VULN>")) {
// Store our current value of copy
tmpCopy = copy;
copy = true;
String aLine2 = in.readLine();
String aLine3 = in.readLine();
String nameLine = in.readLine();
if (list.contains(nameLine.trim())) {
textArea1.append("Skipping: " + nameLine + "\n");
copy = false;
while (!(aLine.trim().equals("</VULN>"))) {
aLine = in.readLine();
}
continue; // this would skip the writing out to file part
} else {
list.add(nameLine.trim());
textArea1.append("::: List is now :::");
textArea1.append(list.toString() + "\n");
}
if (copy) {
out.write(aLine);
out.newLine();
out.write(aLine2);
out.newLine();
out.write(aLine3);
out.newLine();
out.write(nameLine);
out.newLine();
}
} else if (copy) {
out.write(aLine);
out.newLine();
}
// after we have written to file, if the line was a close vuln, switch copy back to original value
if (aLine.trim().equals("</VULN>")) {
copy = tmpCopy;
}
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
copy = false;
}
// Now lets add the close checklist tag we omitted before
try {
out.write("</iSTIG>");
out.write("</STIGS>");
out.write("</CHECKLIST>");
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Java has extensive, highly informative documentation. Keep it bookmarked. Refer to it first, whenever you have difficulty. You'll find it's frequently helpful.
In this case, the documentation for FileWriter says:
The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.
If you want to be sure your file will be written as UTF-8, replace this:
FileWriter fstream = null;
BufferedWriter out = null;
try {
fstream = new FileWriter(mergedFile, false);
with this:
Writer fstream = null;
BufferedWriter out = null;
try {
fstream = new OutputStreamWriter(new FileOutputStream(mergedFile), StandardCharsets.UTF_8);
For those, who use FileWriter in order to append to an existing file, the following will work
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), StandardCharsets.UTF_8)) {
//code
}
You can just run it with the command java -Dfile.encoding=UTF-8 -jar yourjar.jar.
Follow this for more info.
I'm implementing a small tool in Java. I have a excel document and from every sheet I need to generate a .sql file. I've created an sql file model, which I have to read from for every excel sheet then replace a value and write it back to another .sql file. The problem is I use a for where I loop through my sheets and for every sheet I need to read that sql file, modify it and export it somewhere else. I get a "Stream closed" error, and I don't know how to close my buffer and/or my InputStream properly. Can you guys help me out with this ?
This is my code:
This gets everything from the file and converts it to a String
public String getString(InputStream is) throws IOException {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
String line;
try {
reader = new BufferedReader(new InputStreamReader(is));
while ((line = reader.readLine()) != null) {
sb.append(line + System.lineSeparator());
}
} catch (IOException ex) {
ex.printStackTrace();
}
return sb.toString();
}
This is used to export the file
public void exportFile(String text, String path, String name, String extension) {
BufferedWriter output = null;
try {
File sqlFile = new File(path + name + extension);
output = new BufferedWriter(new FileWriter(sqlFile));
output.write(text);
} catch (IOException e) {
e.printStackTrace();
logger.severe("Unable to write to file!\n");
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
logger.severe("Unable to close buffer\n");
}
}
}
}
And this a the part of my run() method, which uses the code above:
ClassLoader loader = this.getClass().getClassLoader();
InputStream createTableInputStream = loader.getResourceAsStream("val_table_create.sql");
if (createTableInputStream == null) {
logger.severe("No tempalte found for creating table!\n");
return;
}
List<Sheet> bookSheets = getSheets(book);
for (Sheet sheet : bookSheets) {
setHeader(table, sheet);
String exportText = getString(createTableInputStream);
exportText = exportText.replaceAll(TABLE_NAME, tableName);
// exportText = exportText.replaceAll(VAL_DATA_TYPE, valDataType);
// exportText = exportText.replaceAll(MSG_TEXT_DATA_TYPE, messageDataType);
exportFile(exportText, absoluteWorkspacePath + File.separator + outputPath + File.separator, tableName, ".sql");
}
if (createTableInputStream != null) {
createTableInputStream.close();
}
The Problem is in this method:
public String getString(InputStream is) throws IOException {
You close the the reader and stream at the end. (When you close the reader the streams in it are automatic close.
Edit: You should close the reader. getString(InputStream is) throws IOException returns always the same String or? Read it before you go in the loop and reuse the String everytime.
String exportText = getString("val_table_create.sql");
for (Sheet sheet : bookSheets) {
setHeader(table, sheet);
String newExportText = exportText.replaceAll(TABLE_NAME, tableName);
messageDataType);
exportFile(newExportText, absoluteWorkspacePath + File.separator + outputPath + File.separator, tableName, ".sql");
}
Change your getString Method to this:
public String getString(String resourceName) throws IOException {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
String line;
try {
InputStream createTableInputStream reader.getResourceAsStream(resourceName);
reader = new BufferedReader(new InputStreamReader(is));
while ((line = reader.readLine()) != null) {
sb.append(line + System.lineSeparator());
}
} catch (IOException ex) {
ex.printStackTrace();
}
return sb.toString();
}
and close there all the streams. Now you have one place where you load your file.
createTableInputStream will be closed for the first time you call getString method so for next sheet in loop you will get stream closed.
It's a better practice to close the stream in the method who created it. You should close the stream in run method instead.
If I didn't miss anything you should be able to run this code, just need a trace.log file in your project root folder.
I don't get what's happening. I just declare some readers / writers and try to read from the file. I get an instant null and the file seems to be empty. WHY?!
import java.io.*;
public class StubLogHandler {
private String name = "";
private String path = "";
public StubLogHandler (String filePath, String fileName) {
this.name = fileName;
this.path = filePath;
}
// THIS IS THE PESCKY BUGGER
public void testReadWrite() {
this.fixPath();
File file = new File (this.path+this.name);
try ( FileReader fileReader = new FileReader(file);
FileWriter fileWriter = new FileWriter(file);
BufferedReader reader = new BufferedReader(fileReader);
BufferedWriter writer = new BufferedWriter(fileWriter);) {
System.out.println("Works, I think.");
String line = "";
while (line != null) {
line = reader.readLine();
System.out.println(line);
// Should get a coupl'a lines, instead I get instant null
// Before you ask, no, the file is not initially empty
}
} catch (FileNotFoundException fnfe) {
System.out.println("File Not Found");
} catch (IOException ioe) {
System.out.println("Could not read or write to file");
}
}
private void fixPath () {
if (this.path.isEmpty())
return;
char lastChar = this.path.charAt(this.path.length()-1);
if (lastChar != '\\')
this.path += "\\"; // In case user forgets the final '\'
}
public String getAbsolutePath() {
this.fixPath();
return new File(this.path+this.name).getAbsolutePath();
}
}
public class Start {
public static void main (String[] args) {
Start.testStuff();
}
private static void testStuff() {
StubLogHandler log = new StubLogHandler("","trace.log");
System.out.println(log.getPath()+log.getName());
System.out.println(log.getAbsolutePath());
log.testReadWrite();
}
}
EDIT
Output:
trace.log
D:\Personal\Java\Workspaces\Default\Practice\trace.log
Works, I think.
null
Creating that writer:
try ( FileReader fileReader = new FileReader(file);
FileWriter fileWriter = new FileWriter(file); // here
will immediately truncate that file in preparation for writing. e.g.
File x = new File("X");
FileWriter fw = new FileWriter(x);
will immediately erase the contents of the pre-existing file X
Normal reading and separately writing to the same file does not work.
FileReader and FileWriter are already buffered I believe. I personally do not use them, as they use the default platform encoding, which is gives unportable data.
And then the end of file is indicated by readLine returning null, hence do:
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
System.out.println(line);
// Should get a coupl'a lines, instead I get instant null
// Before you ask, no, the file is not initially empty
}
Maybe be you want do something like:
Path fpath = Paths.get(this.path+this.name);
List<String> lines = Files.readAllLines(fpath, StandardCharsets.UTF_8);
... process the lines
Files.write(fpath, lines, StandardCharsets.UTF_8);
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.