BufferedReader does not copy files - java

I 've made the code below for copying a file and its contents.
static void copyFile(File inFile, String destination) {
if (inFile.isFile()) {
try {
String str = destination + "//" + inFile.getName();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(inFile),"UTF-8"));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(str), false), "UTF-8"));
String line;
try {
while((line = br.readLine()) != null) {
bw.write(line);
System.out.println(line);
}
} catch (IOException ex) {
Logger.getLogger(JavaApplication10.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(JavaApplication10.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(JavaApplication10.class.getName()).log(Level.SEVERE, null, ex);
}
} else if( inFile.isDirectory()) {
String str = destination + "\\" + inFile.getName();
File newDir = new File( str );
newDir.mkdir();
for( File file : inFile.listFiles())
copyFile(file, newDir.getAbsolutePath());
}
}
The code creaes the files at the destination as it should but the .txt files are empty. The part into the while loop
bw.write(line);
doesn't work
System.out.println(line);
works.

You need to close your Writer in order to make him flush the stream. this can either be done using the newer try with ressources method (preferred):
String str = destination + "//" + inFile.getName();
// note the paranthesis here, notfing that this is has to be closed after leaving the try block.
try (
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(inFile), "UTF-8"));
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(new File(str), false), "UTF-8"))) {
String line;
try {
while ((line = br.readLine()) != null) {
bw.write(line);
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
or using a finally block:
BufferedWriter bw = null;
BufferedReader br = null;
try {
String str = destination + "//" + inFile.getName();
br = new BufferedReader(new InputStreamReader(new FileInputStream(inFile), "UTF-8"));
bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(new File(str), false), "UTF-8"));
String line;
try {
while ((line = br.readLine()) != null) {
bw.write(line);
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
} finally {
try {
if(bw != null)
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (br != null)
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
additionally either the IDE or the compiler should warn you for not closing them.

you forget call bw.flush() method after write finished;
while((line = br.readLine()) != null ){
bw.write(line );
System.out.println( line );
}
bw.flush();
Buffered io remember call flush method;

You can try this
FileWriter fw = new FileWriter(inFile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(line);

Related

Use try-with-resources or close this "BufferedReader" in a "finally" clause

Been looking for a way to fix this issue. Read all the previous answers but none helped me out.
Could it be any error with SonarQube?
public class Br {
public String loader(String FilePath){
BufferedReader br;
String str = null;
StringBuilder strb = new StringBuilder();
try {
br = new BufferedReader(new FileReader(FilePath));
while ((str = br.readLine()) != null) {
strb.append(str).append("\n");
}
} catch (FileNotFoundException f){
System.out.println(FilePath+" does not exist");
return null;
} catch (IOException e) {
e.printStackTrace();
}
return strb.toString();
}
}
You are not calling br.close() which means risking a resource leak. In order to reliably close the BufferedReader, you have two options:
using a finally block:
public String loader(String FilePath) {
// initialize the reader with null
BufferedReader br = null;
String str = null;
StringBuilder strb = new StringBuilder();
try {
// really initialize it inside the try block
br = new BufferedReader(new FileReader(FilePath));
while ((str = br.readLine()) != null) {
strb.append(str).append("\n");
}
} catch (FileNotFoundException f) {
System.out.println(FilePath + " does not exist");
return null;
} catch (IOException e) {
e.printStackTrace();
} finally {
// this block will be executed in every case, success or caught exception
if (br != null) {
// again, a resource is involved, so try-catch another time
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return strb.toString();
}
using a try-with-resources statement:
public String loader(String FilePath) {
String str = null;
StringBuilder strb = new StringBuilder();
// the following line means the try block takes care of closing the resource
try (BufferedReader br = new BufferedReader(new FileReader(FilePath))) {
while ((str = br.readLine()) != null) {
strb.append(str).append("\n");
}
} catch (FileNotFoundException f) {
System.out.println(FilePath + " does not exist");
return null;
} catch (IOException e) {
e.printStackTrace();
}
return strb.toString();
}
Seems like you just want to read all lines from a file. You could use this:
public String loader(String FilePath) {
try(Scanner s = new Scanner(new File(FilePath).useDelimiter("\\A")) {
return s.hasNext() ? s.next() : null;
} catch(IOException e) {
throw new UncheckedIOException(e);
}
}
The code you wrote is indeed leaking resources as you're not closing your BufferedReader. The following snippet should do the trick:
public String loader(String filePath){
String str = null;
StringBuilder strb = new StringBuilder();
// try-with-resources construct here which will automatically handle the close for you
try (FileReader fileReader = new FileReader(filePath);
BufferedReader br = new BufferedReader(fileReader);){
while ((str = br.readLine()) != null) {
strb.append(str).append("\n");
}
}
catch (FileNotFoundException f){
System.out.println(filePath+" does not exist");
return null;
}
catch (IOException e) {
e.printStackTrace();
}
return strb.toString();
}
If you're still having issues with this code, then yes, it's SonarQubes fault :-)

Why is the code asking to catch IOException

I amwriting a program using try catch but the code is asking to surround InputStreamReader and BufferedReader with try-catch to catch IOException or declare IOException using throws. But why is it asking to do so when I am using catch to the IOException.
Here is the code:
public class BufferedReader3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
InputStreamReader r=null;
BufferedReader br=null;
String name="";
try
{
r =new InputStreamReader(System.in);
br =new BufferedReader(r);
while(!name.equals("stop"))
{
System.out.println("Enter data: ");
name=br.readLine();
}
System.out.println("data is: "+name);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
br.close();
r.close();
}
}
}
in finally block close() calls can also throw IOException. So the compiler complains about that because IOException is of type Checked Exception you should also handle this case.
let's try to handle this with;
make use of try with resources
String name = "";
try ( InputStreamReader r = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(r); ){
while (!name.equals("stop")) {
System.out.println("Enter data: ");
name = br.readLine();
}
System.out.println("data is: " + name);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
another try catch block in finally
InputStreamReader r = null;
BufferedReader br = null;
String name = "";
try {
r = new InputStreamReader(System.in);
br = new BufferedReader(r);
while (!name.equals("stop")) {
System.out.println("Enter data: ");
name = br.readLine();
}
System.out.println("data is: " + name);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
br.close();
r.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
make use of deprecated org.apache.commons.io.IOUtils.closeQuietly(Closeable ...)
InputStreamReader r = null;
BufferedReader br = null;
String name = "";
try {
r = new InputStreamReader(System.in);
br = new BufferedReader(r);
while (!name.equals("stop")) {
System.out.println("Enter data: ");
name = br.readLine();
}
System.out.println("data is: " + name);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
finally {
IOUtils.closeQuietly(br, r);
}

Reading and writing a CSV from/to a path

I would like to print line by line the file located in some directory with:
private void readWeatherDataByColumn() {
FileInputStream is = null;
try {
is = new FileInputStream(sourceDirectory);
String line = "";
BufferedReader br = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Prints throwable details
e.printStackTrace();
}
}
I get the following output:
05-21 20:13:42.018 4170-4170/com.soialab.askaruly.camera_sensor I/System.out: ������ ftypisom������isomiso2avc1mp41������
Anyone has any clues?
This must be output
05-22 17:13:22.676 5955-5955/com.soialab.askaruly.camera_sensor I/System.out: 1,22:28:23,42,92,66,224,40,0.28,0.02,0.05
05-22 17:13:22.677 5955-5955/com.soialab.askaruly.camera_sensor I/System.out: 2,22:28:24,48,92,191,224,64,0.28,0.02,0.05
Add the below code where you want to read CSV file.
String csvFileString = readFile(selectedFile.getAbsolutePath()); // path of you selected CSV File
InputStream stream = null;
try {
stream = new ByteArrayInputStream(csvFileString.getBytes(StandardCharsets.UTF_8.name()));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
ReadCsv csv = new ReadCsv(stream);
List<String[]> results = new ArrayList<String[]>();
results = csv.read();
public static String readFile(String theFilePathString) {
String returnString = "";
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream((theFilePathString)), "UTF8"));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
reader.close();
returnString = stringBuilder.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return returnString;
}
ReadCsv.Class
public class ReadCsv {
InputStream in;
public ReadCsv(InputStream in) {
this.in = in;
}
public List<String[]> read() {
List<String[]> results = new ArrayList<String[]>();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] row = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
results.add(row);
}
} catch (IOException e) {
throw new RuntimeException("Error reading CSV File " + e);
} finally {
try {
in.close();
} catch (IOException e) {
throw new RuntimeException("Error closing inputstream " + e);
}
}
return results;
}
}
Thank you for the comments and replies!
I figured out the problem. The string sourceDirectory was of the video file, not the original ".csv" text document. Therefore, some encoding problem occured, as mentioned by #TimBiegeleisen.
Now, it works totally fine with the same code. My bad, sorry...

FileSystemException even after closing buffers

I have this problem java.nio.file.FileSystemException: The process cannot access the file because it is being used by another process. and I can't understand why. The System.err.println(e.getFile()); says the file that causing the exception is the groupFile, but I close the Buffers before using it with the closeBuffers().
what could be the problem with my code?
File groupFile = getFile(_grp +File.separator+ mensagem.getGroup().getName()+".txt");
ServerLogHandler group2SLH = linkHandlerToFile(groupFile);
if(group2SLH.getGroupAdmin().equals(mensagem.getUser().getName())){
try{
File temp = createFile(_grp +File.separator+"temp.txt");
group2SLH.closeBuffers();
deleteAndWrite(membro2.getName(), groupFile, temp);
Files.move(temp.toPath(), groupFile.toPath(), REPLACE_EXISTING);
temp.delete();
}catch(FileSystemException e){
System.err.println(e.getFile());
e.printStackTrace();
}
}
public void closeBuffers(){
try {
this.in.close();
this.out.flush();
this.out.close();
} catch (IOException e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
public static void deleteAndWrite(String deleteThis, File in, File out){
try {
BufferedReader in2 = new BufferedReader(new FileReader(in));
BufferedWriter out2 = new BufferedWriter(new FileWriter(out, true));
String s;
StringBuilder sb = new StringBuilder();
while((s = in2.readLine()) != null){
if(!s.equals(deleteThis)){
sb.append(s+System.getProperty("line.separator"));
out2.write(sb.toString());
}
}
in2.close();
out2.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Java webpanel commands not saving

I have a java app that gets commands from a webpanel, and when it executes a command, it saves somewhere so that it knows that it has executed already. then when it next executes a command, it checks the list before executing the command, this works fine one a PC, but on a mac, it seems to not work.
it saves the commands, but when it checks for new commands, it executes all previous commands aswell.
n3.data contains:
1,2,3,4,
each command is given an id (in this case 1 2 3 and 4), the app is supposed to check what command ids it has used and then execute if the id is not in the specified file (n3.data)
here is the code.
public void save(int id) {
String osName = System.getProperty("os.name");
if(osName.contains("Windows")){
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(System.getProperty("user.home") + "\\app.data", true));
bw.write(id + ",");
bw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
} else if(osName.contains("Mac")){
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(System.getProperty("user.home") + "/n3.data", true));
bw.write(id + ",");
bw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void createNew() {
String osName = System.getProperty("os.name");
File win = new File(System.getProperty("user.home") + "\\app.data");
File mac = new File(System.getProperty("user.home") + "/n3.data");
if(osName.contains("Windows") && !win.exists()){
try {
new File(System.getProperty("user.home") + "\\app.data").createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}else if(osName.contains("Mac") && !mac.exists()){
try {
new File(System.getProperty("user.home") + "/n3.data").createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void saveNew() {
String osName = System.getProperty("os.name");
if(osName.contains("Windows")){
StringBuilder sb = new StringBuilder();
for (int i : processedIds) {
sb.append(i + ",");
}
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(System.getProperty("user.home") + "\\app.data"));
bw.write(sb.toString());
bw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}else if(osName.contains("Mac")){
StringBuilder sb = new StringBuilder();
for (int i : processedIds) {
sb.append(i + ",");
}
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(System.getProperty("user.home") + "/n3.data"));
bw.write(sb.toString());
bw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void loadSave() throws IOException {
String osName = System.getProperty("os.name");
if(osName.contains("Windows")){
File file = new File(System.getProperty("user.home") + "\\app.data");
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
for (String s : sb.toString().split(",")) {
try {
processedIds.add(Integer.parseInt(s));
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
file.createNewFile();
}
}else if(osName.contains("Mac")){
File file = new File(System.getProperty("user.home") + "/n3.data");
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
for (String s : sb.toString().split(",")) {
try {
processedIds.add(Integer.parseInt(s));
} catch (Exception e) {
e.printStackTrace();
}
}
} else if (!file.exists()){
file.createNewFile();
}
}
}
I figured it out, anyone having the same problem, the code doesn't check properly if the file exists or not. just fix that and it should work.

Categories