More specifically, how could I write code that could create a scanner for any text file that the user enters? For instance, one user might want to scan text from "foo.txt," and another might want to read from "bar.txt." How do I compensate for this?
You can simply make a function that opens a file and returns the reader so that you can read each line:
public BufferedReader readFromFile(String path) {
try {
return new BufferedReader(new FileReader(path));
} catch (IOException e) {
e.printStackTrace();
}
}
Then use the BufferedReader which it returns and iterate through each line! Hope it helps!
You can take the path to the file as an input to the program. For taking input, you can have a look at http://www.programmingsimplified.com/java/source-code/java-program-take-input-from-user
Once you have this path in a variable, you can replace the hardcoded file names by this variable instead.
Related
I wanted to know if there is any method in java to access the contents of the file in the computer.
For example if I want to make a word guessing game in which I want to access the words kept in a file randomly.
(I heard of something called "FileReader" but can't understand how to use it.)
Hope you understand what I mean.
Thanks!!
You can also read an entire text file as a List with Files.readAllLines . You can do it like this (read and print):
List<String> sl= Files.readAllLines(Paths.get("test1.txt"));
for (String s:sl) {
System.out.println(s);
}
Another option is to use Files.newBufferedReader like this:
try (BufferedReader br= Files.newBufferedReader(Paths.get("test1.txt")))
{
String line;
while ((line=br.readLine())!=null) System.out.println(line);
}
The try(){ } construct is called try-with-resorces, it closes the open file object (br in this case) automatically when finished. It is vital for writing, and is a good coding practice for reading.
You can read contents of File like this.
public void readFile(String fileName){ //Pass file's absolute path
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = null;
while((line=reader.readLine())!=null){
System.out.println(line);
}
}
I have been looking for the past hour or so trying to find the reason for this, but have found nothing. It is a very small text file (only 4 characters at most), thus the reason I did not bother with a BufferedReader or BufferedWriter. The problem lies in the fact that while I have the writer put the variable into the file and even close the file, it does not actually keep the change in the file. I have tested this by checking the file immediately after running the method containing this code.
try {
int subtract = Integer.parseInt(secMessage[2]);
try {
String deaths = readFile("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt", Charset.defaultCharset());
FileWriter write = new FileWriter("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt");
int comb = Integer.parseInt(deaths) - subtract;
write.write(comb);
write.close();
sendMessage(channel, "Death count updated to " + comb);
} catch (IOException e) {
e.printStackTrace();
}
} catch (NumberFormatException e) {
e.printStackTrace();
sendMessage(channel, "Please use numbers to modify death count");
}
EDIT: Since it was asked, here is my readFile message:
static String readFile(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
I have already tested it and it returns the contents without error.
EDIT2: Posting the readFile method made me think of something to try, so I removed the call to it (code above also updated) and tried it again. It now writes to the file, but does not write what I want. New question will be made for this.
FileWriter write = new FileWriter(readFile("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt", Charset.defaultCharset()));
You're trying to write a file named after the contents of deaths.txt. It's possible that you intend to be writing to the file itself.
From http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html
FileWriter(String fileName)
Constructs a FileWriter object given a file name.
FileWriter write = new FileWriter(readFile("C:/Users/Samboni/Documents/Stuff For Streaming/deaths.txt", Charset.defaultCharset()));
Currently you are using the contents of the file instead of the file name.
I'm trying to write a program that reads a file (which is a Java source file), makes an Arraylist of certain specified values from that file. and outputs that Arraylist into another resulting file.
I'm using PrintWriter to make the new resulting file. This is a summarised version of my program:
ArrayList<String> exampleArrayList = new ArrayList<String>();
File actualInputFile = new File("C:/Desktop/example.java");
PrintWriter resultingSpreadsheet= new PrintWriter("C:/Desktop/SpreadsheetValues.txt", "UTF-8");
FileReader fr = new FileReader(actualInputFile);
BufferedReader br = new BufferedReader(fr);
String line=null;
while ((line = br.readLine()) != null) {
// code that makes ArrayList
}
for (int i = 0; i < exampleArrayList.size(); i++) {
resultingSpreadsheet.println(exampleArrayList.get(i));
}
resultingSpreadsheet.close();
The problem is that when i run this, nothing gets printed to the resultingSpreadsheet. It's completely empty.
BUT, this program works perfectly (meaning that it prints out everything correctly to the resultingSpreadsheet file) when I replace:
File actualInputFile = new File("C:/Desktop/example.java");
which is the file that I want as my input file, and which has a size of 481 KB,
with:
File smallerInputFile = new File("C:/Desktop/smallerExample.txt");
which is really just a smaller .txt example version of the .java source file, and it has a size of 1.08 KB.
I've tried a few things including flushing the PrintWriter, wrapping it around FileWriter, copy-pasting all the code from the .java file into a text file in case it was an extension problem, but these don't seem to work.
I'm starting to think it must be because of the size of the file that the PrintWriter makes, but it's very possible that that's not the problem. Perhaps I need to put everything in a stream (like it says here: http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html)? If so, how would I do that?
Why is reading the bigger actualInputFile and outputting its data correctly such a problem, when everything works fine for the smallerInputFile?
Can anyone help with this?
Check for exceptions while writing to the the excel sheet , because i really don't think its a problem of size. Below is the sample code that is executing successfully and the file size was approx 1 MB.
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("D:\\AdminController.java"));
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();
}
}
}
}
This should go as a comment, but I do not have the rep. In the documentation it has both write methods and print methods. Have you tried using write() instead?
I doubt it's the size of the file, it may be between the two files you are testing one is .txt, and the other is .java
EDIT: Probably second suggestion of the two. First is just something I noticed with the docs.
The methods of PrintWriter do not throw Exception. Call the checkError() method which would flush the stream as well as return true if an error occurred. It is quite possible that an error occurred processing the larger file, an encoding error for instance.
Check your program. When the file is empty it means that your program doesn't close the PrintWriter before finishing the program.
For example you may have a return in a part of your program which cause that resultingSpreadsheet.close(); have not being run.
this is the code that i have found in the internet for reading the lines of a file and also I use eclipse and I passed the name of files as SanShin.txt in its argument field. but it will print :
Error: textfile.txt (The system cannot find the file specified)
Code:
public class Zip {
public static void main(String[] args){
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
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
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
please help me why it prints this error.
thanks
...
// command line parameter
if(argv.length != 1) {
System.err.println("Invalid command line, exactly one argument required");
System.exit(1);
}
try {
FileInputStream fstream = new FileInputStream(argv[0]);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Get the object of DataInputStream
...
> java -cp ... Zip \path\to\test.file
When you just specify "textfile.txt" the operating system will look in the program's working directory for that file.
You can specify the absolute path to the file with something like new FileInputStream("C:\\full\\path\\to\\file.txt")
Also if you want to know the directory your program is running in, try this:
System.out.println(new File(".").getAbsolutePath())
Your new FileInputStream("textfile.txt") is correct. If it's throwing that exception, there is no textfile.txt in the current directory when you run the program. Are you sure the file's name isn't actually testfile.txt (note the s, not x, in the third position).
Off-topic: But your earlier deleted question asked how to read a file line by line (I didn't think you needed to delete it, FWIW). On the assumption you're still a beginner and getting the hang of things, a pointer: You probably don't want to be using FileInputStream, which is for binary files, but instead use the Reader set of interfaces/classes in java.io (including FileReader). Also, whenever possible, declare your variables using the interface, even when initializing them to a specific class, so for instance, Reader r = new FileReader("textfile.txt") (rather than FileReader r = ...).
I want to read a file in java. And then, I want to delete a line from that file without the file being re-written.
How can I do this?
Someone suggested me to read/write to a file without the file being re-written with the help of RandomAccessFile. How to write data to a file through java?
Specifically, that files contains lines. One line contains three field - id, name and profession - separated by \t. I want to read that file through a Reader or InputStream or any other way and then search for a line that has the specified keyword (say 121) and then wants to delete that whole line.
This operation needs to be performed without the whole file being re-written
I don't think you can alter a file on a filesystem in any way without writing to it, including deleting a line.
Do you mean you want to write the file without altering the file's metadata, like the last modified time?
Based on your updated question:
I don't think you can do what you're asking to do here. You can't remove bytes from a file once the file has been written, note no deleteByte or removeByte methods in RandomAccessFile.
I suggest moving the content of your file to a database - that allows this kind of record-oriented operation.
The alternative is, you have to rewrite the file. Sorry!
"Lines" are an abstract concept -- they're just an arbitrary sequence of bytes terminated by "\n". BufferedWriters and their ilk don't support textual editing in this way, so you'll have to rewrite the file in its entirety.
In general, what you want to do is:
open a reader
read content into some suitable data structure
close the reader
change data/records which need to be changed in this data structure
open a FileWriter with append == false
write content of data structure to resulting file
close FileWriter
add a marker in your lines saying if your line is deleted or not : this will make a software delete instead od a hardware delete.
if you have to insert new lines, you then can reuse those that are marked as deleted.
The below code searchs the line or fields in a single text file reads the file line by line
then the line or fields can be replaced by " " or any other string. Here we use the pattern and Matcher classes.
If this not clearing your question do let me know.
import java.io.;
import java.util.regex.;
import java.util.Properties;
public class DeleteLine
{
public static void main(String[] args)
{
BufferedReader br = null;
try
{
String line=null;
File f = new File("d:/xyz.txt");
String replaceString=properties.getProperty("replaceAll.String");
;
br = new BufferedReader(new FileReader("d:/giri/scjp/");
while ( (line = br.readLine()) != null )//BufferedReader contains readline method
{
Pattern p=Pattern.compile(searchString);/*here u an specify the line u want to delete */
Matcher m=p.matcher(line);
line=m.replaceAll(replaceString);/*here replace String u can " " so that it will be emptied */
System.out.println(line);
}
//System.out.println(line);
}
}
}
br = new BufferedReader(new FileReader("d:/xyz.txt"));
String line = null;
}
catch (FileNotFoundException e)
{
System.out.println("File couldnt find");
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}