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();
}
}
Related
The input stream is not closing even though i closed it.
I don't know how to close the input stream, because I'm still new to this
The below code is for Sending data
while (socket!=null)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder out = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
out.append(line);
}
handler.obtainMessage(MESSAGE_READ_DONE,out.toString()).sendToTarget();
reader.read();
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (reader != null){
reader.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
}
this is for writeTheData
public void write(byte[] bytes)
{
new Thread(new Runnable() {
#Override
public void run() {
if (outputStream!=null){
try {
outputStream.write(bytes);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}else {
Toast.makeText(MainActivity.this, "null data", Toast.LENGTH_SHORT).show();
}
}
}).start();
}
}
Thanks in advance for help!
You can close the buffered Reader like this.Think closing the buffered Reader will solve your problem.
reader.close();
reader != null always return true because BufferedReader was initialized. There is no method or workaround to check whether the reader is closed or not.
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 :-)
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...
I used following method to write data to a file in one android application
private void writeFileToInternalStorage() {
String eol = System.getProperty("line.separator");
BufferedWriter writer = null;
try{
writer = new BufferedWriter(new OutputStreamWriter(openFileOutput("myFile.txt", MODE_WORLD_WRITEABLE|MODE_WORLD_READABLE)));
writer.write("Hello world!");
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (writer != null)
{
try
{
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
Then I tried to read that file from another android application using this method
private void readFileFromInternalStorage(){
String eol = System.getProperty("line.separator");
BufferedReader input = null;
try
{
input = new BufferedReader(new InputStreamReader(openFileInput("myFile1.txt")));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = input.readLine()) != null)
{
buffer.append(line + eol);
}
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(buffer.toString().trim());
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (input != null)
{
try
{
input.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
Second method can't read the file. I added read write permissions also, but it shows only blank screen. What can be the error and how can I correct that ??. I'm new to Android programming and need your help.
Thanks!
The problem is
openFileOutput("myFile.txt", MODE_WORLD_WRITEABLE|MODE_WORLD_READABLE))
The documentation says:
This file is written to a path relative to your app within the
So the case is you are writing file in path relative to application 1 and trying to read it from
path relative to application 2.
You should be able to call Environment.getExternalStorageDirectory() to get the root path to the SD card and use that to create a FileOutputStream. From there, just use the standard java.io routines.
Look below snippet to write file to SD card.
private void writeToSDCard() {
try
{
File file = new File(Environment.getExternalStorageDirectory(),
"filename");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("Hello World");
writer.close();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Look below snippet to read file saved on SD card.
private void readFileFromSDCard() {
File directory = Environment.getExternalStorageDirectory();
// Assumes that a file article.rss is available on the SD card
File file = new File(directory + "/article.rss");
if (!file.exists()) {
throw new RuntimeException("File not found");
}
Log.e("Testing", "Starting to read");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Your best bet is to place it into the scdcard into something like /sdcard/Android/data/package/shared/
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.