How to open a text file? - java

I can't figure out for the life of me what is wrong with this program:
import java.io.*;
public class EncyptionAssignment
{
public static void main (String[] args) throws IOException
{
String line;
BufferedReader in;
in = new BufferedReader(new FileReader("notepad encypt.me.txt"));
line = in.readLine();
while(line != null)
{
System.out.println(line);
line = in.readLine();
}
System.out.println(line);
}
}
The error message says that the file can't be found, but I know that the file already exists. Do I need to save the file in a special folder?

The error is "notepad encypt.me.txt".
Since your file is named "encypt.me.txt", you can't put a "notepad" in front of its name. Moreover, the file named "notepad encypt.me.txt" probably didn't exist or is not the one that you want to open.
Additionally, you have to provide the path ( absolute or relative ) of your file if it's not located in your project folder.
I will take the hypothesis that your are on a Microsoft Windows system.
If your file has as absolute path of "C:\foo\bar\encypt.me.txt", you will have to pass it as "C:\\foo\\bar\\encypt.me.txt" or as "C:"+File.separatorChar+"foo"+File.separatorChar+"bar"+File.separatorChar+encypt.me.txt".
If it's still not working, you should verify that the file :
1) Exist at the path provided.
You can do it by using the following piece of code:
File encyptFile=new File("C:\\foo\\bar\\encypt.me.txt");
System.out.println(encyptFile.exists());
If the path provided is the right one, it should be at true.
2) Can be read by the application
You can do it by using the following piece of code:
File encyptFile=new File("C:\\foo\\bar\\encypt.me.txt");
System.out.println(encyptFile.canRead());
If you have the permission to read the file, it should be at true.
More informations:
Javadoc of File
Informations about Path in computing

import java.io.*;
public class Test {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "temp.txt";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}

package com.mkyong.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Reference: http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/

Related

Displaying the contents of a textfile by typing the filename in a java program?

Write a program that reads in a file and displays its contents. Get the input filename from the command line. For example, if your program is in the file Display.class, you would enter on the command line:
java Display t1.txt
to display the content file t1.txt.
How can this be done?
you can use FileReader or BufferedReader to read the contents of file. below code may be helpful to you
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Display {
public static void main(String[] args) {
if(args.length > 0) {
String fileName = args[0];
try {
File file = new File(fileName);
if(file.exists() && file.isFile() ) {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
System.out.println("FileContents are...");
while((line = br.readLine()) != null) {
System.out.println(line);
}
}else{
System.out.println("File Not Found");
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Taking data from multiple files and moving to one file

I some code that takes a file called wonder1.txt and writes the date in that file to another file. Lets say I have more files like wonder2.txt, wonder3.txt, wonder4.txt. How do I write the rest in the same file.
import java.io.*;
import java.util.*;
import java.lang.*;
public class alice {
public static void main(String[] args) throws FileNotFoundException, IOException {
String fileName = ("/Users/DAndre/Desktop/Alice/wonder1.txt");
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = br.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
line = br.readLine();
}
/**
* Pass original file content as string to another method which
* creates new file with same content.
*/
newFile(stringBuilder.toString());
} finally {
br.close();
}
}
public static void newFile(String fileContent) {
try {
String newFileLocation = "/Users/DAndre/Desktop/Alice/new1.txt";
PrintWriter writer = new PrintWriter(newFileLocation);
writer.write(fileContent);//Writes original file content into new file
writer.close();
System.out.println("File Created");
} catch (Exception e) {
e.printStackTrace();
}
}
}
If you have list of files, then you can loop over them one by one. Your current code moves inside the loop.
The easier way would be to put all the files in one folder and read from it.
Something like this :
File folder = new File("/Users/DAndre/Desktop/Alice");
for (final File fileEntry : folder.listFiles()) {
String fileName = fileEntry.getAbsolutePath();
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = br.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
line = br.readLine();
}
/**
* Pass original file content as string to another method which
* creates new file with same content.
*/
newFile(stringBuilder.toString());
} finally {
br.close();
}
}

Code deletes the content of the file rather than replacing a text

In my below code I wanted to replace the text "DEMO" with "Demographics" but instead of replacing the text it deletes the entire content of the text file.
Contents inside the file:
DEMO
data
morning
PS: I'm a beginner in java
package com.replace.main;
import java.io.*;
public class FileEdit {
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
String readLine, replacedData;
try {
bw = new BufferedWriter(
new FileWriter(
"Demg.ctl"));
br = new BufferedReader(
new FileReader(
"Demg.ctl"));
System.out.println(br.readLine()); //I Get Null Printed Here
while ((readLine = br.readLine())!= null) {
System.out.println("Inside While Loop");
System.out.println(readLine);
if (readLine.equals("DEMO")) {
System.out.println("Inside if loop");
replacedData = readLine.replaceAll("DEMO","Demographics");
}
}
System.out.println("After While");
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You open a Writer to your file, but you don't write anything. This means that your file is replaced with an empty file.
Besides this you also need to close your writer, not just the reader.
And last but not least, your if condition is wrong.
if (readLine.equals("DEMO")) {
should read
if (readLine.contains("DEMO")) {
Otherwise it would only return true if your line contained "DEMO" but nothing else.
I'm updating the answer to my own question.
package com.replace.main;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileEdit
{
public static void main(String args[])
{
try
{
BufferedReader reader = new BufferedReader(new FileReader("Demg.ctl"));
String readLine = "";
String oldtext = "";
while((readLine = reader.readLine()) != null)
{
oldtext += readLine + "\r\n";
}
reader.close();
// To replace the text
String newtext = oldtext.replaceAll("DEMO", "Demographics");
FileWriter writer = new FileWriter("Demg.ctl");
writer.write(newtext);
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

why it is always showing file is not found

public static void main(String[] args) throws IOException {
String filename = "C:\\audiofile.wav";
InputStream in = null;
try{
in = new FileInputStream(filename);
}
catch(FileNotFoundException ex){
System.out.println("File not found");
}
AudioStream s = null;
s = new AudioStream(in);
AudioPlayer.player.start(s);
}
i have written this code in netbeans. Name of my audio file is audiofile.wav. But it is all time showing the exception "file not found". Can anyone help me ???
root folders in C drive of Windows Vista and above are protected by UAC. This requires you to run the java executable in Administrative mode.
However, you can shift the wav file elsewhere, where UAC will not interfere(like Documents folder of your currently logged in user) or the root of a different drive(Eg. D:\ and E:)
Also, make sure that the audiofile.wav is indeed in the said location(C:\audiofile.wav)
I think first, you should paste your exception code!
then, I think java I/O support the both two way:
"C:/audiofile.wav"
"C:\audiofile.wav"
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
// write your code here
String fileLocation = "C:\\1.diff";
String fileLocation1 = "C:/1.diff";
try {
FileInputStream f = new FileInputStream(fileLocation);
BufferedReader reader = new BufferedReader(new InputStreamReader(f));
String line = reader.readLine();
System.out.println("11111111111111111111111111");
while (line != null) {
// Process line
line = reader.readLine();
System.out.println(line);
}
System.out.println("11111111111111111111111111");
} catch (Exception ex) {
System.out.println(ex);
}
try {
FileInputStream ff = new FileInputStream(fileLocation1);
BufferedReader reader1 = new BufferedReader(new InputStreamReader(ff));
String line1 = reader1.readLine();
System.out.println("2222222222222222222222222");
while (line1 != null) {
// Process line
line1 = reader1.readLine();
System.out.println(line1);
}
System.out.println("2222222222222222222222222");
} catch (Exception ex) {
System.out.println(ex);
}
}
}
it works. I don't know what you did, anyway paste your error msg!
====
```
private static void B() {
String filename = "C:\\test.wav";
InputStream in = null;
try {
in = new FileInputStream(filename);
} catch (FileNotFoundException ex) {
System.out.println("File not found");
}
try {
AudioStream s = new AudioStream(in);
AudioPlayer.player.start(s);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
```
it works!
Try just placing your file in a different location and see what happens
ProjectRootDir
audiofile.wav
src
And running this String
String filename = "audiofile.wav";

Unable to rename file

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))

Categories

Resources