Modify or Delete Data in a File - java

Today I was trying the algorithm for modifying and deleting data inside a file using Java in Windows platform.
1st : create a temporaryFile
2nd : write the data you wanted inside the originalFile into a String and to the temporaryFile
3rd : rename temporaryFile to originalFile.
The Code:
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class testing{
private static String temp;
public static void main(String [] args)
{
try{
File tempFile = File.createTempFile("haha\\temporary", ".txt"); //create a temporary file in haha folder
FileWriter writer = new FileWriter(tempFile);
Scanner input = new Scanner(new File("haha\\testing.txt")); //get input from testing.txt
temp = input.next();
writer.write(temp);
writer.close();
File origFile = new File("haha\\testing.txt");
tempFile.renameTo(origFile);
}
catch ( FileNotFoundException fileNotFoundException ){}
catch(IOException ioException){}
}
}
In the above code , the textFile to be edited is located inside a folder name haha which is located inside another folder together with the testing.class.I've tried this code to no avail , the originalTextFile has no changes .

If you have your file in the same directory, you don't need to pass the path to the File constructor.
Scanner input = new Scanner(new File("testing.txt"));
This should do it.

You need to close the Scanner object to make the changes, the underlying operating system has a file lock that must be released.
input.close();
File origFile = new File("haha\\testing.txt");

Related

Storing a String as a file in database in java

I want to turn the content of a String variable into (I don't know the the correct term) a file and store it in my database. I do not need the file physically and only need it stored in the database so I can download it later in the Frontend.
I want the operation to happen automatically in the Backend (Rest API turns a String variable into a file with the extension .pem and stores it in the database). Is it possible ? Any help is appreciated.
maybe what I think is you want to store some data in a File.If wrong, please inform me.
You need to import some packages for that :-
import java.io.File;
import java.io.Scanner;
import java.io.FileWriter;
import java.util.Arrays;
Use the following code :-
public void writetoFile(String pathtofile, String text)
{
try{
File file = new File(pathtofile);
FileWriter fw = new FileWriter(file);
fw.write(text);
fw.close();
}
catch(IOException e){
System.out.println(e);
}
}
//If you want to read content from the file, you can get all lines in an array or other method you wish.
public String [] readfromFile(String path){
try{
File file = new File(path);
Scanner scan = new Scanner(file);
String [] out = new String[1];
int i=0;
while(scan.hasNextLine()){
out[i]=scan.nextLine();
i++;
out = Arrays.copyOf(out,out.legnth+1);
}
}catch(IOException e){
System.out.println(e);
}
return out;
}

read from one file, modify and output to another file in java

The assignment is to read a file, create a new file that matches the input file but has numbers lines added
I have several examples to copy from. I have tried new File(), new FileReader() and BufferedReader(). I can't seem to get any data out of the input file
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
public class Hw1_43 {
public static void main(String[] args) throws FileNotFoundException
{
// Prompt user for input file name
Scanner in = new Scanner(System.in);
System.out.print("Enter input file name: ");
String inputFileName = in.next(); // instantiate input file name for later use
Scanner inputFile = new Scanner(new FileReader(inputFileName));
//ArrayList<String> line = new ArrayList();
int counter = 0;
while (inputFile.hasNextLine()) {
String line = inputFile.nextLine();
System.out.println(counter + line);
counter ++;
}
System.out.println(inputFileName);
}
}
Also after I get the input file to read and write it into an output file, where is the output file so I can look at it to make sure it is correct?
FileReader only reads from a file. You need to create a FileWriter, which writes to a file (e.g. FileWriter outputFile = new FileWriter ("C:/tmp/output_file.txt")). As you read from the FileWriter, prepend the line numbers to each line, then write to the FileWriter.
I recommend using BufferedReader instead of Scanner. You can then use then uses the .readLine() or .lines() methods, the latter can be streamed into a BufferedWriter.

Another java.io.FileNotFoundException (The system cannot find the file specified) thread

I've created a basic notepad text file (e.g., text-file.txt) and have tried placing this file in multiple file paths for my code to retrieve, but I can't seem to get this to work. Basically, I'm wanting to take the content of text-file.txt and create a second file where everything is in all caps.
Here is my code:
package abc123;
import java.util.Scanner;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class abc123
{
public static void main (String [] args) throws IOException
{
Scanner in = new Scanner(System.in);
System.out.print("Please provide the name of your input file: ");
String inFileName = in.nextLine();
System.out.print("Please indicate what you'd like to name your output file: ");
String outFileName = in.nextLine();
FileReader reader = new FileReader(inFileName);
PrintWriter writer = new PrintWriter(outFileName);
Scanner fileReader = new Scanner(reader);
while(fileReader.hasNext())
{
String line = fileReader.nextLine();
line = line.toUpperCase();
writer.println(line);
}
fileReader.close();
writer.close();
System.out.println("The process is now complete. Please check your output file. Thank you.");
}
}
I'm a Java newbie, so a simple solution (and comments, as always) that I can grasp at this point would be super helpful. Thanks!
if the file isn't in the same folder as your java class, you have to give java full-path to find the file. be sure you also type the extension of the file, like ".txt".

Unable to read file with Scanner in Java

I'm attempting to pass a File object to the Scanner constructor.
File file = new File("in.txt");
try{
Scanner fileReader = new Scanner(file);
}
catch(Exception exp){
System.out.println(exp.getMessage());
}
I have an in.txt in the root of the project, src and bin directories in case I'm getting the location wrong. I have tried giving absolute paths as well. This line
Scanner fileReader = new Scanner(file);
always fails. Execution jumps to the end of main. If I misspell the name of the file, I get a FileNotFoundException. I'm on an Ubuntu 12.10 Java 1.7 with OpenJDK
I am running on linux and this is how you need to do it
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Testing {
public static void main(String args[]) throws IOException {
Scanner s = null;
try {
//notice the path is fully qualified path
s = new Scanner(new File("/tmp/one.txt"));
while (s.hasNext()) {
System.out.println(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
}
}
here is the result :
source from Java Docs
If you do: File file = new File("in.txt"); in your java program
(let's assume it is named Program.java) then the file in.txt should
be in the working directory of your program at runtime. So if you
run your program like this:
java Program
or
java package1.package2.Program
and you are in /test1/test2/ when running this command,
then the file in.txt needs to be in /test1/test2/.

why is Scanner's hasNext() method initially returning false for a non-empty text file?

I'm trying to write some text to a file. I have a while loop that is supposed to just take some text and write the exact same text back to the file.
I discovered that the while loop is never entered because Scanner thinks there's no more text to read. But there is.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteToFile {
public static void main(String[] args) throws FileNotFoundException {
String whatToWrite = "";
File theFile = new File("C:\\test.txt");
Scanner readinput = new Scanner(theFile);
PrintWriter output = new PrintWriter(theFile);
while (readinput.hasNext()) { //why is this false initially?
String whatToRead = readinput.next();
whatToWrite = whatToRead;
output.print(whatToWrite);
}
readinput.close();
output.close();
}
}
The text file just contains random words. Dog, cat, etc.
When I run the code, text.txt becomes empty.
There was a similar question: https://stackoverflow.com/questions/8495850/scanner-hasnext-returns-false which pointed to encoding issues. I use Windows 7 and U.S. language. Can I find out how the text file is encoded somehow?
Update:
Indeed, as Ph.Voronov commented, the PrintWriter line erases the file contents! user2115021 is right, if you use PrintWriter you should not work on one file. Unfortunately, for the assignment I had to solve, I had to work with a single file. Here's what I did:
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteToFile {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> theWords = new ArrayList<String>();
File theFile = new File("C:\\test.txt");
Scanner readinput = new Scanner(theFile);
while (readinput.hasNext()) {
theWords.add(readinput.next());
}
readinput.close();
PrintWriter output = new PrintWriter(theFile); //we already got all of
//the file content, so it's safe to erase it now
for (int a = 0; a < theWords.size(); a++) {
output.print(theWords.get(a));
if (a != theWords.size() - 1) {
output.print(" ");
}
}
output.close();
}
}
PrintWriter output = new PrintWriter(theFile);
It erases your file.
You are trying to read the file using SCANNER and writing to another file using PRINTWRITER,but both are working on same file.PRINTWRITER clear the content of the file to write the content.Both the class need to work on different file.

Categories

Resources