I have created a Java program that reads a file and shows the same in the output. But my output is coming like unable to open file test.txt. Any help?
package test;
import java.io.*;
public class Test {
public static void main(String[] args) {
// The name of the file to open.
String fileName = "test.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();
}
}
}
Try to put the "whole" path to the file, instead of only the name. Put it like "User/.../.../test.txt".
Hope it helps.
Related
I have tried to implement a simple program to delete a particular text from a file, some how it is not able to delete it. I am reading entire file content into a temp file , delete the user input string from it and update the content to the original file.
Any help would be highly appreciated.
public class TextEraser{
public static void main(String[] args) throws IOException {
System.out.print("Enter a string to remove : ");
Scanner scanner = new Scanner(System. in);
String inputString = scanner. nextLine();
// Locate the file
File file = new File("/Users/lobsang/documents/input.txt");
//create temporary file
File temp = File.createTempFile("file", ".txt", file.getParentFile());
String charset = "UTF-8";
try {
// Create a buffered reader
// to read each line from a file.
BufferedReader in = new BufferedReader(new FileReader(file));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
String s = in.readLine();
// Read each line from the file and echo it to the screen.
while (s !=null) {
s=s.replace(inputString,"");
s = in.readLine();
}
writer.println(s);
// Close the buffered reader
in.close();
writer.close();
file.delete();
temp.renameTo(file);
} catch (FileNotFoundException e1) {
// If this file does not exist
System.err.println("File not found: " + file);
}
}
After replace with input string, write string immediate in file.
while (s != null) {
s = s.replace(inputString, "");
writer.write(s);
// writer.newLine();
s = in.readLine();
}
For new line , use BufferedWriter in place of PrintWriter, it contains method newLine()
writer.newLine();
Remove this
writer.println(s);
I have a file that contains score data for a game (the player name and their final score.
I want to open the file and have the data contained to be displayed so that it would look something like
PLAYER SCORE
------ -----
John 1000
Steve 2000
The file is definitely saving the data that I want but I cannot get it to display the data.
I have tried various things along the lines of:
public static void loadScores() {
boolean fileIsValid;
String filename = "";
File file;
do {
fileIsValid = true;
clrscr();
System.out.println("\t\t\t\t\t\t\t\t\tLEADERBOARDS");
printWave();
if (!fileIsValid) {
System.out.print("\n\nSorry, commander, your file name: " + filename + " does not exist.");
}
System.out.println("");
filename = "scores.gz";
file = new File(filename);
if (!file.exists()) {
fileIsValid = false;
}
} while (!fileIsValid);
System.out.println(file);
pressKey();
}
This is how I would do it.
public static void loadScores() {
File file = null;
try{
file = new File("scores.gz");
if (!file.exists()) {
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
fileReader.close();
} else {
System.out.print("\n\nSorry, commander, your file name: " + filename + " does not exist.");
}
}
catch(IOException e) {
e.printStackTrace();
}
}
Note: Your original code will sit in an infinite loop until the file is created! Also there is no sleep in your loop, thus you will query the file system continuously without a wait period.
This doesn't require 3rd party libraries but Apache commons has some nice util classes, also for reading files: http://commons.apache.org/proper/commons-io/description.html
This code is reading a bunch of .java files and finding "public [classname]" or "private [classname]" and adding "System.out.println([classname])" to that line.
The problem is When I write that line back in I end up with a blank file
Can anyone see what I am doing wrong?
private static void work(ArrayList<File> fileList) {
for (int i = 0; i < fileList.size(); i++) {
replaceLines(fileList.get(i));
}
}
public static void replaceLines(File file) {
String path = file.getPath();
String fileNameLong = file.getName();
String fileName = null;
if (fileNameLong.contains(".java")) {
fileName = fileNameLong.substring(0, file.getName().indexOf("."));
}
if (fileName != null && fileName != "") {
System.out.println(fileName);
try {
//prepare reading
FileInputStream in = new FileInputStream(path);
BufferedReader br = new BufferedReader(
new InputStreamReader(in));
//prepare writing
FileWriter fw = new FileWriter(file);
PrintWriter out = new PrintWriter(fw);
String strLine;
while ((strLine = br.readLine()) != null) {
// Does it contain a public or private constructor?
boolean containsPrivateCon = strLine.contains("private "
+ fileName);
boolean containsPublicCon = strLine.contains("public "
+ fileName);
if (containsPrivateCon || containsPublicCon) {
int lastIndexOfBrack = strLine.lastIndexOf("{");
while (lastIndexOfBrack == -1) {
strLine = br.readLine();
lastIndexOfBrack = strLine.lastIndexOf("{");
}
if (lastIndexOfBrack != -1) {
String myAddition = "\n System.out.println(\""
+ fileName + ".java\"); \n";
String strLineModified = strLine.substring(0,
lastIndexOfBrack + 1)
+ myAddition
+ strLine.substring(lastIndexOfBrack + 1);
strLine = strLineModified;
}
}
out.write(strLine);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
If you want to write to the same file you're reading from, you should either write to a copy of the file (different filename) and then rename the output file, or use RandomAccessFile interface to edit a file in-place.
Usually, the first solution will be much easier to implement than the second one; unless the files are huge (which is probably not the case with .java files), there is no real reason to use the second.
You forgot to flush and close the file. PrintWriter keeps a buffer and unless you explicitly flush() it, the data will (un)happily sit in the buffer and it will never be written to the output.
So you need to add this before the line catch (Exception e) {
out.flush();
out.close();
Note that this is only necessary for PrintWriter and PrintStream. All other output classes flush when you close them.
could someone please provide a hint how i can go about reading data from a variable (some string file) which holds my random computations and store the output in a text file and probably some functionality for working with it.
thanks,
steliyan
I have 2 examples for you; the first is reading from a text file, the second is writing to one.
import java.io.*;
class FileRead {
public static void main(String args[]) {
try{
BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
br.close();
} catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
import java.io.*;
class FileWrite {
public static void main(String args[]) {
String var = "var";
try {
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(var);
//Close the output stream
out.close();
} catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
How do you read and display data from .txt files?
BufferedReader in = new BufferedReader(new FileReader("<Filename>"));
Then, you can use in.readLine(); to read a single line at a time. To read until the end, write a while loop as such:
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
If your file is strictly text, I prefer to use the java.util.Scanner class.
You can create a Scanner out of a file by:
Scanner fileIn = new Scanner(new File(thePathToYourFile));
Then, you can read text from the file using the methods:
fileIn.nextLine(); // Reads one line from the file
fileIn.next(); // Reads one word from the file
And, you can check if there is any more text left with:
fileIn.hasNext(); // Returns true if there is another word in the file
fileIn.hasNextLine(); // Returns true if there is another line to read from the file
Once you have read the text, and saved it into a String, you can print the string to the command line with:
System.out.print(aString);
System.out.println(aString);
The posted link contains the full specification for the Scanner class. It will be helpful to assist you with what ever else you may want to do.
In general:
Create a FileInputStream for the file.
Create an InputStreamReader wrapping the input stream, specifying the correct encoding
Optionally create a BufferedReader around the InputStreamReader, which makes it simpler to read a line at a time.
Read until there's no more data (e.g. readLine returns null)
Display data as you go or buffer it up for later.
If you need more help than that, please be more specific in your question.
I love this piece of code, use it to load a file into one String:
File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\\Z").next();
Below is the code that you may try to read a file and display in java using scanner class. Code will read the file name from user and print the data(Notepad VIM files).
import java.io.*;
import java.util.Scanner;
import java.io.*;
public class TestRead
{
public static void main(String[] input)
{
String fname;
Scanner scan = new Scanner(System.in);
/* enter filename with extension to open and read its content */
System.out.print("Enter File Name to Open (with extension like file.txt) : ");
fname = scan.nextLine();
/* this will reference only one line at a time */
String line = null;
try
{
/* FileReader reads text files in the default encoding */
FileReader fileReader = new FileReader(fname);
/* always wrap the FileReader in BufferedReader */
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
/* always close the file after use */
bufferedReader.close();
}
catch(IOException ex)
{
System.out.println("Error reading file named '" + fname + "'");
}
}
}
If you want to take some shortcuts you can use Apache Commons IO:
import org.apache.commons.io.FileUtils;
String data = FileUtils.readFileToString(new File("..."), "UTF-8");
System.out.println(data);
:-)
public class PassdataintoFile {
public static void main(String[] args) throws IOException {
try {
PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
pw1.println("Hi chinni");
pw1.print("your succesfully entered text into file");
pw1.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
String line;
while((line = br.readLine())!= null)
{
System.out.println(line);
}
br.close();
}
}
In Java 8, you can read a whole file, simply with:
public String read(String file) throws IOException {
return new String(Files.readAllBytes(Paths.get(file)));
}
or if its a Resource:
public String read(String file) throws IOException {
URL url = Resources.getResource(file);
return Resources.toString(url, Charsets.UTF_8);
}
You most likely will want to use the FileInputStream class:
int character;
StringBuffer buffer = new StringBuffer("");
FileInputStream inputStream = new FileInputStream(new File("/home/jessy/file.txt"));
while( (character = inputStream.read()) != -1)
buffer.append((char) character);
inputStream.close();
System.out.println(buffer);
You will also want to catch some of the exceptions thrown by the read() method and FileInputStream constructor, but those are implementation details specific to your project.