I'm trying to make a file delete after it has 20 characters in it. I have looked at every single Stack Overflow question about this, and no answer worked. I have looked every where, and nothing works. File.delete(); does not work for me. It writes a file, and every time a button is pressed it adds a "1" to it. If there are 20 1's, than it needs to delete the file.
Sample Code:
String fileName1 = "data1.txt";
try {
FileWriter fw = new FileWriter(fileName1, true);
try (BufferedWriter bw = new BufferedWriter(fw)) {
bw.write("1");
bw.close();
} catch (IOException ex) {
Logger.getLogger(StudentRandomizerJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (IOException ex) {
Logger.getLogger(StudentRandomizerJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
try {
Scanner scanner = new Scanner(new FileReader("data1.txt"));
String scannerData1 = scanner.nextLine();
if (scannerData1.equals("11111111111111111111")) {
//In here is where its supposed to delete the file.
}
} catch (FileNotFoundException ex) {
Logger.getLogger(StudentRandomizerJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
Seems to work okay for me...
for (int index = 0; index < 50; index++) {
String fileName1 = "data1.txt";
try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName1, true))) {
bw.write("1");
} catch (IOException ex) {
ex.printStackTrace();
}
boolean deleteMe = false;
try (Scanner scanner = new Scanner(new FileReader("data1.txt"))) {
String scannerData1 = scanner.nextLine();
if (scannerData1.length() >= 20) {
deleteMe = true;
}
} catch (IOException ex) {
ex.printStackTrace();
}
if (deleteMe) {
File file = new File(fileName1);
if (!file.delete()) {
System.out.println("!! Could not delete " + file);
} else {
System.out.println(file + " was deleted");
}
System.out.println(file + " exists = " + file.exists());
}
}
Prints
data1.txt was deleted
data1.txt exists = false
data1.txt was deleted
data1.txt exists = false
Maybe you need to check to see if you have the correct permissions to delete the file (but if you have write permissions, you should be able to delete it) and you're deleting the file you think you're deleting
Related
I am designing a program that saves the index location for specific characters from a message. Then, I need to retrieve these characters according to their index location. I kept the locations for these characters in a .txt file. I retrieved them, but at the end, I got this message "Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index 120 out of bounds for length 120".
My codes:
int n;
String s;
int lineNumCount = 0;
String coverText = stegoMsg.getText(); // get the stego text from the textfield
int k = coverText.length(); // get the length for the stego text
int lineNumb = 1;
Scanner myFile = null;
try{
Scanner file = new Scanner(new File("location.txt"));//location.txt is the file that has the locations for the characters
myFile = file;
}catch (FileNotFoundException e){
System.out.println("File does not found");
}
while (myFile.hasNextLine()){
//Count the Number of the lines in location.txt
//1. Read the File
File fileLocation = new File("location.txt");
if(fileLocation.exists()){
try {
FileReader fr = new FileReader(fileLocation);
LineNumberReader lr = new LineNumberReader(fr); //2. Read the lines for location.txt
while((lr.readLine()) !=null){
lineNumCount++;
}
// System.out.println("Total Number of the Lines " + lineNumCount);
} catch (FileNotFoundException ex) {
Logger.getLogger(ExtPage.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ExtPage.class.getName()).log(Level.SEVERE, null, ex);
}
for(int x = 0; x<lineNumCount; ++x){
try{
String line = Files.readAllLines(Paths.get("location.txt")).get(lineNumb);
// System.out.println("Line First " + line);
BufferedReader bufrd = new BufferedReader(new FileReader("SFile.txt")); //SFile.txt is the file that has the messsage that I need to take the location for the specific characters
int nn = Integer.parseInt(line);
s = bufrd.readLine();
System.out.println("The Location " + nn + " is : "+ s.charAt(nn)); // read the character that has this location
lineNumb++;
}catch(IOException e){
System.out.println("Line 334");
}
}
}
}
myFile.close();
}
Is it possible to guide me on how I can solve the exception?
I appreciate any help you can provide.
Here is the solution ...
int n;
String s;
int lineNumCount = 0;
String coverText = stegoMsg.getText(); // get the stego text from the textfield
int k = coverText.length(); // get the length for the stego text
int lineNumb = 1;
Scanner myFile = null;
try{
Scanner file = new Scanner(new File("location.txt"));
myFile = file;
}catch (FileNotFoundException e){
System.out.println("File does not found");
}
try{
while (myFile.hasNext()){
//Count the Number of the lines in location.txt
//1. Read the File
File fileLocation = new File("C:\\Users\\Farah\\Dropbox\\Steganography codes\\NewStegoTech\\location.txt");
if(fileLocation.exists()){
try {
FileReader fr = new FileReader(fileLocation);
LineNumberReader lr = new LineNumberReader(fr); //2. Read the lines for location.txt
while((lr.readLine()) !=null){
lineNumCount++;
}
} catch (FileNotFoundException ex) {
Logger.getLogger(ExtPage.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ExtPage.class.getName()).log(Level.SEVERE, null, ex);
}
try{
String line = Files.readAllLines(Paths.get("location.txt")).get(lineNumb);
// System.out.println("Line First " + line);
BufferedReader bufrd = new BufferedReader(new FileReader("Stego File.txt"));
int nn = Integer.parseInt(line);
s = bufrd.readLine();
System.out.println("The Loocation " + nn + " is : "+ s.charAt(nn)); // read the character that has this location
lineNumb++;
}catch(IOException e){
System.out.println(e);
}
}
}
}catch(IndexOutOfBoundsException e)
{
System.out.println("Finish reading file");
}
myFile.close();
i am having some problem in java, i wanted to remove number 5 to number 7 and save them into a new file called RevisedNumbers.txt, is there any way to do that? this is my code so far
import java.util.Scanner;
import java.io.*;
public class Txt {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
File myObj = new File("Numbers1to10.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
try {
Writer writer = new PrintWriter("Numbers1to10.txt");
for(int i = 1; i <= 10; i++)
{
writer.write("Number" + i);
writer.write("\r\n");
}
writer.close();
File readFile = new File("Numbers1to10.txt");
Scanner read = new Scanner(readFile);
while (read.hasNextLine())
System.out.println(read.nextLine());
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
try {
File myObj = new File("RevisedNumbers.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
the desired output on the new file will be
Number 1
Number 2
Number 3
Number 4
Number 8
Number 9
Number 10
One possible solution might be using an additional file.
While reading the contents of the first file ("Numbers1to10.txt"), if values are within 5 to 7, then write it into the second file ("RevisedNumbers.txt"), otherwise write it into the additional file.
Now the additional file contains values that you need in the first file. So copy all contents of the additional file into the first file.
Here is a sample code.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileWriteMain {
static void _write1to10(String locationWithFileName) {
try {
File file = new File(locationWithFileName);
boolean fileAlreadyExist = file.exists();
if (fileAlreadyExist) {
System.out.println("File already exists!");
} else {
System.out.println("New file has been created.");
}
FileWriter fileWriter = new FileWriter(file);
for (int i = 1; i <= 10; i++) {
fileWriter.write("Number " + i);
fileWriter.append('\n');
}
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static File _getFile(String locationWithFileName) {
File file = null;
file = new File(locationWithFileName);
return file;
}
// it reads a file and print it's content in console
static void _readFile(Scanner scanner) {
while (scanner.hasNextLine()) {
String currLine = scanner.nextLine();
System.out.println(currLine);
}
}
// read contents from sourceFile file and copy it into destinationFile
static void _copyFromOneFileToAnother(File sourceFile, File destinationFile) throws IOException {
FileWriter destFileWriter = new FileWriter(destinationFile);
Scanner scanner = new Scanner(sourceFile);
while (scanner.hasNextLine()) {
String currLine = scanner.nextLine();
destFileWriter.write(currLine);
destFileWriter.append('\n');
}
destFileWriter.close();
}
public static void main(String[] args) {
String locationWithFileName = "E:\\FileWriteDemo\\src\\Numbers1to10.txt"; // give your file name including it's location
_write1to10(locationWithFileName);
System.out.println("File writing done!");
File file1 = _getFile(locationWithFileName);
try {
// creating file 2
String locationWithFileName2 = "E:\\FileWriteDemo\\src\\RevisedNumbers.txt";
File file2 = _getFile(locationWithFileName2);
FileWriter fileWriter2 = new FileWriter(file2);
// creating a temporary file
String tempFileLocationWithName = "E:\\FileWriteDemo\\src\\temporary.txt";
File tempFile = _getFile(tempFileLocationWithName);
FileWriter tempFileWriter = new FileWriter(tempFile);
Scanner scanner = new Scanner(file1);
while (scanner.hasNextLine()) {
String currLine = scanner.nextLine();
// split the word "Number" from integer
String words[] = currLine.split(" ");
for (int i = 0; i < words.length; i++) {
// System.out.println(words[i]);
try {
int num = Integer.parseInt(words[i]);
if (num >= 5 && num <= 7) {
// writing to second file
fileWriter2.write(currLine);
fileWriter2.append('\n');
} else {
// writing to temporary file
tempFileWriter.write(currLine);
tempFileWriter.append('\n');
}
} catch (NumberFormatException e) {
// current word is not an integer, so don't have to do anything
}
}
}
fileWriter2.close();
tempFileWriter.close();
_copyFromOneFileToAnother(tempFile, file1);
System.out.println("\nContents of first file");
_readFile(new Scanner(file1));
System.out.println("\nContents of second file");
_readFile(new Scanner(file2));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Hope it helps!
Happy coding.
I'm working on a multi-threaded web-server for a school project. I should be able to go into the localhost on my browser and request 3 different files (.htm, .jpeg,.pdf). However, when I do this for a .htm file with the picture also inside of it (2 requests) the .htm file appears in browser but I get many broken pipe socket exceptions for each write I try to do on the picture (Assignment requires to write 1024 bytes at a time). Something is clearly wrong with the way I have implemented this but I am at a loss as to where the connection is being closed when I try to write for the second file?
I tried a few different things to try and fix this including a loop when trying to read the socket input stream but I think that defeats the purpose of the multi-threaded server.
The server:
while(true){
try {
sock = servSock.accept(); // Handles the connection
// Connection received log
System.out.println("Connection received: " + new Date().toString() + " at " + sock.getInetAddress() + sock.getPort());
HTTP pro = new HTTP(sock); // Client handler
pro.run();
ServerThread serverThread = new ServerThread(pro);
// Starts ServerThread
serverThread.start();
} catch (Exception e){
System.out.println(e);
}
}
HTTP:
public void run(){
// Try to open reader
try{
readSock = new BufferedReader(new InputStreamReader(sock.getInputStream()));
} catch (Exception e){
System.out.println(e);
}
// Open output stream
try{
this.out = new DataOutputStream(sock.getOutputStream());
this.printOut = new PrintWriter(sock.getOutputStream());
} catch (Exception e){
System.out.println(e);
}
// Try to read incoming line
try {
this.reqMes = readSock.readLine();
} catch (IOException e) {
e.printStackTrace();
}
StringTokenizer st = new StringTokenizer(reqMes);
// Parse the request message
int count = 0;
while(st.hasMoreTokens()){
String str = st.nextToken();
if (count == 1){
this.fileName = "." + str;
}
count += 1;
}
System.out.println("File name received.");
File file = null;
try {
file = new File(this.fileName);
this.f = new FileInputStream(file); // File input stream
this.fileExists = true;
System.out.println("File " + this.fileName + " exists.");
} catch (FileNotFoundException e) {
System.out.println(e);
this.fileExists = false;
System.out.println("File does not exist.");
}
byte[] buffer = new byte[1024];
// Write status line
if (this.fileExists) {
System.out.println("Trying to write data");
try{
this.out.writeBytes("HTTP/1.0 " + "200 OK " + this.CRLF);
this.out.flush();
this.printOut.println("HTTP/1.0 " + "200 OK " + this.CRLF);
// Write Header
this.out.writeBytes("Content-type: " + getMime(this.fileName) + this.CRLF);
this.printOut.println("Content-type: " + getMime(this.fileName) + this.CRLF);
this.out.flush();
// Read file data
byte[] fileData = new byte[1024];
while (this.f.read(fileData) != -1) {
// Write File data
try{
this.out.write(fileData,0,1024);
this.out.flush(); // Flush output stream
} catch (IOException e) {
System.out.println(e);
}
}
System.out.println("Flushed");
} catch (IOException e) {
e.printStackTrace();
}
}
For one .htm file in the browser, the file and html seem to appear fine. But it looks like it makes a second request for a .jpeg file within the html file and the browser gets stuck loading with java.net.SocketException: Broken pipe (Write failed) when writing the data each time at
this.out.write(fileData,0,1024);
Thank you, any help is appreciated.
After much searching among different problems, I found the answer here.
The problem was with the response headers not being formatted properly which led to the connection ending prematurely. Another empty line ("\r\n") must be sent after the header.
The following code now works (this.CRLF is equal to "\r\n"):
public void run(){
// Try to open reader
try{
readSock = new BufferedReader(new InputStreamReader(sock.getInputStream()));
} catch (Exception e){
System.out.println(e);
}
// Open output stream
try{
this.out = new DataOutputStream(sock.getOutputStream()); // Data output
this.printOut = new PrintWriter(sock.getOutputStream()); // Print output
} catch (Exception e){
System.out.println(e);
}
// Try to read incoming line
try {
this.reqMes = readSock.readLine();
} catch (IOException e) {
e.printStackTrace();
}
StringTokenizer st = new StringTokenizer(reqMes);
// Parse the request message
int count = 0;
while(st.hasMoreTokens()){
String str = st.nextToken();
if (count == 1){
this.fileName = "." + str;
}
count += 1;
}
System.out.println("File name received.");
// Initialize file to be sent
File file = null;
// Try to find file and create input stream
try {
file = new File(this.fileName);
this.f = new FileInputStream(file); // File input stream
this.fileExists = true;
System.out.println("File " + this.fileName + " exists.");
} catch (FileNotFoundException e) {
System.out.println(e);
this.fileExists = false;
System.out.println("File does not exist.");
}
byte[] buffer = new byte[1024];
// Write status line
if (this.fileExists) {
System.out.println("Trying to write data");
try{
this.out.writeBytes("HTTP/1.0 " + "200 OK " + this.CRLF);
this.out.flush();
// Write Header
this.out.writeBytes("Content-type: " + getMime(this.fileName) + this.CRLF);
this.out.flush();
this.out.writeBytes(this.CRLF);
this.out.flush();
// Read file data
byte[] fileData = new byte[1024];
int i;
while ((i = this.f.read(fileData)) > 0) {
// Write File data
try{
this.out.write(fileData,0, i);
} catch (IOException e) {
System.out.println(e);
}
}
this.out.flush(); // Flush output stream
System.out.println("Flushed");
closeSock(); // Closes socket
} catch (IOException e) {
e.printStackTrace();
}
I'm making a system to save data into txt.
1 - I've declared the file:
public static final File file = new File("src/window/data.txt");
2 - The system that is not working
public void checkData() throws Exception
{
Scanner scan = new Scanner(file);
if (scan.hasNext() == false)
{
System.out.println("file is empty");
BufferedWriter fileWriter = new BufferedWriter(new FileWriter(file));
fileWriter.write("test");
}
else
{
System.out.println("file is not empty");
}
}
it always return false which means print "file is empty".
I have edited that code with try-catch statement and tried to "data.txt" that contains any data and it works:
public static final File file = new File("data.txt");
public static void main(String[] args) {
try (Scanner scan = new Scanner(file)) {
if (!scan.hasNext()) {
System.out.println("file is empty");
BufferedWriter fileWriter = new BufferedWriter(new FileWriter(file));
fileWriter.write("test");
} else {
System.out.println("file is not empty");
}
} catch (IOException ex) {
System.out.println(ex);
}
}
The output is "file is not empty". Please try out my code and check if the path to your file is really correct.
You could use more recent features of Java, e. g. Path, Paths and Files in order to write a textfile and check for file existence and emptiness.
public static void writeFile(String filePath, List<String> lines) {
try {
Path path = Paths.get(filePath);
boolean exists = Files.exists(path);
System.out.println( "File " + path.getFileName() + " exists: " + exists);
if( exists) {
boolean empty = Files.size(path) == 0;
System.out.println("Empty: " + empty);
}
Files.write(path, lines, StandardCharsets.UTF_8);
System.out.println("File written: " + path.getFileName());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Usage
writeFile("c:/temp/test.txt", Arrays.asList("Some Text"));
i want to print the output in new line how to do this?
Below is the output.
CHILD: Child line one oneCHILD: Child line one twoCHILD: Child line one three
CHILD: Child line two oneCHILD: Child line two twoCHILD: Child line two three
here is my code for it...
try {
fis = new FileInputStream(file);
fileWriterChild = new FileWriter(outputFileForChild);
brChild = new BufferedWriter(fileWriterChild);
fr = new FileReader(file);
br = new BufferedReader(fr);
int child_line_no = 0;
int buffer = 0;
String currentLine = br.readLine();
while (currentLine != null) {
if (currentLine.contains("CHILD:")) {
Files.write(Paths.get("C:/output.child.txt"),
currentLine.getBytes(), StandardOpenOption.APPEND);
}
currentLine = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
fis.close();
}
}
Depends on what do you want to do. Here are my two ways:
Appending one line to the end of file
void WriteLog(String date, String message) {
String logFileName = <path to file>;
File logFile = new File(logFileName);
//make directories
logFile.getParentFile().mkdirs();
try (FileWriter writer = new FileWriter(logFile, true)) {
writer.write(message);
writer.write("\r\n");
} catch (IOException ex) {
Cls_log.LogError("Error writing log - " + ex.toString());
}
}
Writing all strings as lines to file (overwriting file)
public static void WriteABcardLog(Map<String,String> etiquetteCache) {
File logFile = new File(<path to file>);
logFile.getParentFile().mkdirs();
try (PrintWriter writer = new PrintWriter(logFile)) {
Iterator<Map.Entry<String, String>> iterator = etiquetteCache.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
try {
writer.print(entry.getKey() + ";" + entry.getValue() + "\r\n");
} catch (NullPointerException e) {
Cls_log.LogError(e);
}
}
writer.println();
} catch (IOException ex) {
Cls_log.LogError("Error writing etiquette log - " + ex.toString());
}
}