As per the captioned subject, I am not able to delete String from a text file on deployment in tomcat. Although it works absolutely fine in netbeans or eclipse.
When application is deployed it always says 'could not delete file'. Also I am not able to manually delete the file as I get 'Cannot delete file: It is in use by some other programs'.
But I am able to append String to this same text file.
This is the code that I am using to delete String from the file.
package com.pro.model;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RemoveLine {
private String inputFileName = "D:\\Marquee\\Copy of Scroll.txt";
public boolean deleteData(String msg, int pos) throws IOException {
//List msg_remove = null;
System.out.println("msg :" + msg);
BufferedReader reader = null;
try {
File inputFile = new File(inputFileName);
File tempFile = new File("D:\\myTempFile.txt");
reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = msg;
String currentLine;
while ((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String[] trimmedLine = currentLine.split("\\|");
System.out.println("currentLine :" + currentLine);
System.out.println("trimmedLine :" + trimmedLine.length);
for (int i = 0; i < trimmedLine.length; i++) {
int k = i + 1;
System.out.println("Calculating the size of field " + k);
//writer.write("Column " + k + " is " + trimmedLine[i].length());
// is.flush();
// is.newLine();
System.out.println("trimmedLine[i] :" + trimmedLine[i]);
//writer.write(trimmedLine[i] + "|");
System.out.println("trimmedLine[i].equals(lineToRemove) :" + trimmedLine[i].equals(lineToRemove));
//if (trimmedLine[i].equals(lineToRemove)) {
if (i == pos) {
System.out.println("trimmedLine in if:" + trimmedLine[i]);
//writer.flush();
//trimmedLine.replaceAll(currentLine, "");
continue;
}
System.out.println("currentLine :" + currentLine);
//writer.write(currentLine + "|");
writer.write(trimmedLine[i] + "|");
}
}
writer.flush();
reader.close();
writer.close();
if (!inputFile.delete()) {
System.out.println("Could not delete file");
return false;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inputFile)) {
System.out.println("Could not rename file");
return false;
}
return true;
//boolean successful = tempFile.renameTo(inputFile);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
return false;
} finally {
try {
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public List readText() throws FileNotFoundException, IOException {
BufferedReader reader = null;
List msg_after_removed = new ArrayList();
try {
File inputFile = new File(inputFileName);
//File tempFile = new File("C:\\myTempFile.txt");
reader = new BufferedReader(new FileReader(inputFile));
//msg_after_removed = new ArrayList();
if (inputFile.exists()) {
//data = msg1;
FileWriter fileWritter = new FileWriter(inputFile.getPath(), true);
System.out.println("file.getName():" + inputFile.getName());
System.out.println("file.getName():" + inputFile.getPath());
reader = new BufferedReader(new FileReader(inputFile));
String currentLine;
while ((currentLine = reader.readLine()) != null) {
String[] trimmedLine = currentLine.split("\\|");
for (int i = 0; i < trimmedLine.length; i++) {
Bean getdata = new Bean();
System.out.println("trimmedLine in read ==" + trimmedLine[i] + i + "=length=" + trimmedLine.length);
getdata.setMsg(trimmedLine[i]);
String arr[] = trimmedLine[i].split(":");
System.out.println("arr[] in read" + arr[1]);
getdata.setDate(arr[0]);
getdata.setMsg(arr[1]);
msg_after_removed.add(getdata);
//reader.close();
}
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
Bean getdata = new Bean();
getdata.setDate("0");
getdata.setMsg("0");
msg_after_removed.add(getdata);
System.out.println("in catch");
//reader.close();
//return false;
} finally {
if (reader != null) {
reader.close();
}
}
return msg_after_removed;
}
}
I thought maybe Read stream is not closing properly & that is why I am not able to delete/save file manually. But if that was the case, I should also not be able to append String to the file.
Any help is appreciated.
Related
My goal is to write and read to a file to save settings for my app. These settings will be configured by the user and saved into a file called saved_settings.txt
My methodology was to have a separate java class that took care of this, and I would reference that class and its methods when needed.
Right now my code breaks at fos = openFileOutput(fileName, MODE_PRIVATE);
Is this because I have not created a file yet. It just keeps giving me a null pointer exception and I can't seem to understand why.
Thanks in advance for any help.
Java class I call to read or write
package com.example.tipcalculator;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
/*
ReadWrite is a java class that retrieves and saves data to a file
*/
public class ReadWrite extends AppCompatActivity {
//"saved_settings.txt" or "tip_data.txt"
/**
* Creates ReadWrite Object
*/
public ReadWrite() {
}
/**
* Writes to file
* #param text
* #param fileName
*/
public void writeToFile(String text, String fileName) {
FileOutputStream fos = null;
try {
fos = openFileOutput(fileName, MODE_PRIVATE);
fos.write(text.getBytes());
Toast.makeText(this, "Saved to " + getFilesDir() + "/" + fileName,
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Reads from file
* #param fileName
* #return
*/
public String readFromFile(String fileName) {
String text = new String();
FileInputStream fis = null;
try {
fis = openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((text = br.readLine()) != null) {
sb.append(text).append("\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return text;
}
}
The code that is triggered from the save button
private void saveSettings() {
String settings = boxMode + "," + desc1TB.toString() + "," + perc1TB.toString() + "," + desc2TB.toString() + "," + perc2TB.toString() + "," + desc3TB.toString() + "," + perc3TB.toString() + "," + desc4TB.toString() + "," + perc4TB.toString();
readWrite.writeToFile(settings, "saved_settings.txt");
}
import java.io.*;
import java.util.Random;
import java.util.Scanner;
class EncryptDecryptFile{
public String readEncryptionFile()
{
String contentLine1 = "";
//String encryptFilename = Solution.filepath + "EncryptionFile.txt";
BufferedReader br = null;
try
{
br = new BufferedReader(new FileReader("C:\\Users\\HP\\Desktop\\EncryptionFile.txt"));
String contentLine = br.readLine();
while (contentLine != null)
{
contentLine1 = contentLine;
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally
{
try
{
if(br != null)
br.close();
}
catch (IOException ioe)
{
System.out.println("Error in closing the BufferedReader");
}
}
return contentLine1;
}
public void writeDecryptionFile(String message)
{
BufferedWriter bw = null;
//String decryptFilename = Solution.filepath + "DecryptionFile.txt";
try
{
File file = new File("C:\\Users\\HP\\Desktop\\DecryptionFile.txt");
if (!file.exists())
{
file.createNewFile();
FileWriter fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write(message);
}
else
{
FileWriter fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write(message);
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally
{
try
{
if(bw!=null)
bw.close();
}
catch(Exception ex)
{
System.out.println("Error in closing the BufferedWriter"+ex);
}
}
}
}
public class Solution {
public static String filepath = "C:\\Users\\HP\\Desktop\\";
private static String generateString()
{
char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
StringBuilder generatedString = new StringBuilder(20);
Random random = new Random();
for (int i = 0; i < 40; i++) {
char c = chars[random.nextInt(chars.length)];
generatedString.append(c);
}
return generatedString.toString();
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
String message = sc.nextLine();
try{
EncryptDecryptFile f = new EncryptDecryptFile ();
String encryptFilename = Solution.filepath + "EncryptionFile.txt";
String generatedString = generateString();
BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\HP\\Desktop\\EncryptionFile.txt"));
writer.write(generatedString);
writer.close();
if(f.readEncryptionFile().equals(generatedString))
{
f.writeDecryptionFile(message);
String decryptFilename = Solution.filepath + "DecryptionFile.txt";
BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\HP\\Desktop\\DecryptionFile.txt"));
String messageFromFile = reader.readLine();
reader.close();
System.out.println(messageFromFile);
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
When I write in the Decryption.txt file using writeDecryptionFile(message) method the file not accept the message.
There are two method readEncryptionFile() method and writeDecryptionFile(message) method.
readEncryptionFile() read the content from Encryption.txt and it matches with generatedString if it equals true then,
writeDecryptionFile(message) method write the message String message = sc.nextLine(); to the Decryption.txt file.
instead of this you can use library to decrypt and encrypt.
I'm not quite sure, what you are trying to ask, but it seem's like you are missing a 'flush' in writeDecryptionFile
...
bw = new BufferedWriter(fw);
bw.write(message);
bw.flush();
...
without the flush the buffered characters are never written to the stream
https://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#flush()
I am working on a simple server in Java that should have a capability of transferring a file across computers. I am getting a NullPointerException on line 77 of Protocol.class. Here is the stack:
java.lang.NullPointerException
at Protocol.processInput(Protocol.java:77)
at Server.main(Server.java:41)
Why does this happen? There is no null references on line 77!
Client.java:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
public class Client {
private static boolean filein = false;
private static ArrayList<String> fln = new ArrayList<>();
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println(
"Usage: java Client <host name> <port number>");
System.exit(1);
}
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try (
Socket kkSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(kkSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(kkSocket.getInputStream()));
) {
BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser = null;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("#file")) { filein = true;
fromUser = "";}
else if(fromServer.equals("#end#")) {
filein = false;
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showSaveDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
String fname = chooser.getSelectedFile().getAbsolutePath();
File f = new File(fname);
f.createNewFile();
PrintWriter p = new PrintWriter(f);
for(int i = 0; i < fln.size(); i++) {
p.println(fln.get(i));
}
p.close();
JOptionPane.showMessageDialog(null, "File saved!");
}
}
else if (filein == true) {
fln.add(fromServer);
System.out.println(fln.get(fln.size() - 1));
}
if (fromServer.equals("Bye."))
break;
if (!filein) fromUser = stdIn.readLine();
else if (filein) fromUser = "#contintueFileRun";
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
Server.java:
import java.io.*;
import java.net.*;
import static java.lang.System.out;
/**
* Title: FTP Server
* #author Galen Nare
* #version 1.0
*/
public class Server {
public static void main(String[] args) throws IOException {
out.println("Starting server!");
if (args.length != 1) {
System.err.println("Usage: java Server <port number>");
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine, outputLine;
// Initiate conversation with client
Protocol kkp = new Protocol();
outputLine = kkp.processInput("");
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And finally, Protocol.java:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Protocol {
enum ServerState {
STARTING,
WAITING
}
ArrayList<String> lns;
boolean fileout = false;
int i = 0;
private ServerState state = ServerState.STARTING;
public String processInput(String theInput) throws Exception {
String theOutput = "";
if (state == ServerState.STARTING) {
theOutput = "Hello, Client!";
state = ServerState.WAITING;
}
if (!theInput.equals("")) {
if(theInput.length() > 10 && theInput.startsWith("e")) {
if (theInput.substring(0,11).equalsIgnoreCase("executecmd ")) {
theOutput = theInput.substring(11);
System.out.println(theOutput);
try {
#SuppressWarnings("unused")
Process child = Runtime.getRuntime().exec(theInput.substring(11));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
theOutput = "Executed " + theInput.substring(11) + ".";
}
} else if (theInput.equalsIgnoreCase("stop")) {
theOutput = "Stopping Server!";
System.exit(0);
} else if (theInput.equalsIgnoreCase("executecmd")) {
theOutput = "Usage: executecmd <command [-options]>";
} else if (theInput.equalsIgnoreCase("getfile")) {
theOutput = "Usage: getfile <file>";
} else if(theInput.length() > 7 && theInput.startsWith("g")) {
System.out.println("in");
if (theInput.substring(0,8).equalsIgnoreCase("getfile ")) {
theOutput = theInput.substring(8);
File f = new File(theInput.substring(8));
Scanner scan = new Scanner(f);
ArrayList<String> lns = new ArrayList<>();
while(scan.hasNext()) {
lns.add(scan.nextLine());
}
for (int i=0; i < lns.size(); i++) {
System.out.println(lns.get(i));
}
scan.close();
lns.add("#end#");
theOutput = "#file";
fileout = true;
}
} else if (fileout && i < lns.size()) {
theOutput = lns.get(i);
i++;
} else if (fileout && i == lns.size()) {
i = 0;
fileout = false;
} else {
theOutput = "That is not a command!";
}
}
System.out.print(theOutput);
return theOutput;
}
}
Thanks in advance!
You're never initializing lns in Protocol, so it's always a null reference. You may be able to get away with just changing the declaration to:
private List<String> lns = new ArrayList<String>();
(I've made it private and changed the type to List just out of habit...)
You should also consider giving it a more readable name - is it meant to represent lines? If so, call it lines!
(Next, consider why you weren't able to diagnose this yourself. Did you step through this in the debugger? Why did you think there were no null references on line 77? What diagnostic steps did you take in terms of adding extra logging etc? It's important to use errors like this as a learning experience to make future issues more tractable.)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class Test {
List<String> knownWordsArrayList = new ArrayList<String>();
List<String> wordsArrayList = new ArrayList<String>();
List<String> newWordsArrayList = new ArrayList<String>();
String toFile = "";
public void readKnownWordsFile() {
try {
FileInputStream fstream2 = new FileInputStream("knownWords.txt");
BufferedReader br2 = new BufferedReader(new InputStreamReader(fstream2, "UTF-8"));
String strLine;
while ((strLine = br2.readLine()) != null) {
knownWordsArrayList.add(strLine.toLowerCase());
}
HashSet h = new HashSet(knownWordsArrayList);
// h.removeAll(knownWordsArrayList);
knownWordsArrayList = new ArrayList<String>(h);
// for (int i = 0; i < knownWordsArrayList.size(); i++) {
// System.out.println(knownWordsArrayList.get(i));
// }
} catch (Exception e) {
// TODO: handle exception
}
}
public void readFile() {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("Smallville 4x02.de.srt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
String numberedLineRemoved = "";
String strippedInput = "";
String[] words;
String trimmedString = "";
String temp = "";
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
temp = strLine.toLowerCase();
// Print the content on the console
numberedLineRemoved = numberedLine(temp);
strippedInput = numberedLineRemoved.replaceAll("\\p{Punct}", "");
if ((strippedInput.trim().length() != 0) || (!strippedInput.contains("")) || (strippedInput.contains(" "))) {
words = strippedInput.split("\\s+");
for (int i = 0; i < words.length; i++) {
if (words[i].trim().length() != 0) {
wordsArrayList.add(words[i]);
}
}
}
}
HashSet h = new HashSet(wordsArrayList);
h.removeAll(knownWordsArrayList);
newWordsArrayList = new ArrayList<String>(h);
// HashSet h = new HashSet(wordsArrayList);
// wordsArrayList.clear();
// newWordsArrayList.addAll(h);
for (int i = 0; i < newWordsArrayList.size(); i++) {
toFile = newWordsArrayList.get(i) + ".\n";
// System.out.println(newWordsArrayList.get(i) + ".");
System.out.println();
}
System.out.println(newWordsArrayList.size());
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public String numberedLine(String string) {
if (string.matches(".*\\d.*")) {
return "";
} else {
return string;
}
}
public void writeToFile() {
try {
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(toFile);
// Close the output stream
out.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static void main(String[] args) {
Test test = new Test();
test.readKnownWordsFile();
test.readFile();
test.writeToFile();
}
}
How can I read äöüß from file?
Would the string.toLowercase() handle these properly as well?
And when I go to print words containing any of äöüß, how can I print the word properly?
When I print to console I get
Außerdem
weiß
for Außerdem
weiß
How can I fix this?
I tried:
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
But now I'm getting aufkl?ren instead of aufklären and its messing up in other places as well.
Updated the code to see if it would print on the file properly, but I'm just getting one in the file.
You need to read files using the charset which was used to create the file. If you're on a windows machine, that's probably cp1252. So:
BufferedReader br = new BufferedReader(new InputStreamReader(in, "Cp1252"));
If that doesn't work, most text editors are capable of telling you what encoding is used for a given document.
I was trying an exercise of deleting lines from a file not starting with a particular string.
The idea was to copy the desired lines to a temp file, delete the original file and rename the temp file to original file.
My question is I am unable to rename a file!
tempFile.renameTo(new File(file))
or
tempFile.renameTo(inputFile)
do not work.
Can anyone tell me what is going wrong? Here is the code:
/**
* The intention is to have a method which would delete (or create
* a new file) by deleting lines starting with a particular string. *
*/
package com.dr.sort;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class RemoveLinesFromFile {
public void removeLinesStartsWith(String file, String startsWith, Boolean keepOrigFile) {
String line = null;
BufferedReader rd = null;
PrintWriter wt = null;
File tempFile = null;
try {
// Open input file
File inputFile = new File(file);
if (!inputFile.isFile()) {
System.out.println("ERROR: " + file + " is not a valid file.");
return;
}
// Create temporary file
tempFile = new File(file + "_OUTPUT");
//Read input file and Write to tempFile
rd = new BufferedReader(new FileReader(inputFile));
wt = new PrintWriter(new FileWriter(tempFile));
while ((line = rd.readLine()) != null) {
if (line.substring(0, startsWith.length()).equals(startsWith)) {
wt.println(line);
wt.flush();
}
}
rd.close();
if (!keepOrigFile) {
inputFile.delete();
if (tempFile.renameTo(new File(file))) {
System.out.println("OK");
} else {
System.out.println("NOT OK");
}
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
finally {
if (tempFile != null && tempFile.isFile()) {
wt.close();
}
}
}
}
I guess you need to close your PrintWriter before renaming.
if (line.substring(0, startsWith.length()).equals(startsWith))
should instead be the opposite, because we don't want the lines that are specified to be included.
so:
if (!line.substring(0, startsWith.length()).equals(startsWith))