I'm using Scanner to read a file with different extension that a text file normally has but with same content as text file.
If I do use Scanner on text.txt extension then I do get out put but when I perform same task on the different extension but with same content that I don't get any output at all.
After performing different test, it seen that the problem are those characters: “ ”
Any clue why same file with different extension got different behaviors?
file:
“1 line”
2nd line
3 rd line
code:
public static void main(String[] args)
{
String path = "C:\\Users\\user\\Documents\\t1.RANDOM";
File file = new File(path);
StringBuilder sb = new StringBuilder();
try {
Scanner sc = new Scanner(file);
while(sc.hasNextLine())
{
sb.append(sc.nextLine()+"\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(sb);
}
I might think Scanner is doing different stream reading if it doesn't identify a known extension.
Maybe try using the following constructor:
Scanner sc = new Scanner(file, "UTF-8");
Related
So i'm trying to write to a file to use as a save point to access later, but i cant actually get it to write to the file. I'm trying to save the components of a class to access next time I open and run the program, by writing a string with the PIV's to the file as a save method and by using a scanner to search for tags at the beginning of each line to access later. My code so far though, will not actually write to the file. It compiles and runs fine, but the file shows being unchanged after the program runs.
public static void main(String[] args) throws FileNotFoundException, IOException
{
File f = new File("SaveFile");
Scanner sc = new Scanner(f);
String save = new String();
while(sc.hasNextLine())
{
save=sc.nextLine();
}
byte buf[]=save.getBytes();
FileOutputStream fos = new FileOutputStream(f);
for(int i=0;i<buf.length;i++)
fos.write(buf[i]);
if(fos != null)
{
fos.flush();
fos.close();
}
}
If anyone has a way to fix the code or even a better idea for saving please let me know, thanks
You are replacing save value in every single nextLine.
Change this line:
save = sc.nextLine();
to this one:
save += sc.nextLine();
Also, it's better to use a FileWriter when you are writing String to a file.
And because String is immutable, it will be a slow procedure. Consider using StringBuilder or CharBuffer instead of simple solution which I mentioned above.
Look at code included below:
public static void main (String[] args) throws Exception
{
File f = new File("SaveFile");
Scanner sc = new Scanner(f);
StringBuilder builder = new StringBuilder();
while (sc.hasNextLine())
{
builder.append(sc.nextLine() + "\n");
}
String save = builder.toString();
FileWriter writer = new FileWriter(f);
writer.write(save);
writer.close();
}
Also close() implicitly calls flush().
I'm trying to read in a .txt file in but when i use debugger it gets stuck on nextline? Is there some logic error that im doing? It's all being stored into an array through multiple objects:
public static File readFileInfo(Scanner kb)throws FileNotFoundException
{
System.out.println("Enter your file name");
String name = "";
kb.nextLine();
name = kb.nextLine();
File file = new File(name);
return file;
}
The scanner I passed into it is:
Scanner fin = null, kb = new Scanner(System.in);
File inf = null;
inf = FileUtil.readFileInfo(kb);
fin = new Scanner(inf);
You're reading from two different "files" here:
System.in, the standard input (or "terminal"), which you're using to ask the user for a filename
the file with the name you get from the user
When you call name = kb.nextLine();, you're asking the parameter (the Scanner built with System.in) for its next line. Generally, that will actually block ("hang") until it receives another line of input (the filename) from the user. If running from a command line, enter your text into that window; if running in an IDE, switch to the Console tab and enter it there.
As quazzieclodo noted above, you probably only need to call readLine once.
After that, you can open up your second Scanner based on the File that readFileInfo returns, and then you're actually reading from a text file as expected.
Assuming that your intention is to use Scanner to read a text file:
File file = new File("data.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
I have a file, I know that file will always contain only one word.
So what should be the most efficient way to read this file ?
Do i have to create input stream reader for small files also OR Is there any other options available?
Well something's got to convert bytes to characters.
Personally I'd suggest using Guava which will allow you to write something like this:
String text = Files.toString(new File("..."), Charsets.UTF_8);
Obviously Guava contains much more than just this. It wouldn't be worth it for this single method, but it's positive treasure trove of utility classes. Guava and Joda Time are two libraries I couldn't do without :)
Use Scanner
File file = new File("filename");
Scanner sc = new Scanner(file);
System.out.println(sc.next()); //it will give you the first word
if you have int,float...as first word you can use corresponding function like nextInt(),nextFloat()...etc.
Efficient you mean performance-wise or code simplicity (lazy programmer)?
If it is the second, then nothing I know beats:
String fileContent = org.apache.commons.io.FileUtils.readFileToString("/your/file/name.txt")
- Use InputStream and Scanner for reading the file.
Eg:
public class Pass {
public static void main(String[] args){
File f = new File("E:\\karo.txt");
Scanner scan;
try {
scan = new Scanner(f);
while(scan.hasNextLine()){
System.out.println(scan.nextLine());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
- Guava Library handles this beautifully and efficiently.
Use BufferedReader and FileReader classes. Only two lines of code will suffice to read one word/one line file.
BufferedReader br = new BufferedReader(new FileReader("Demo.txt"));
System.out.println(br.readLine());
Here is a small program to do so. Empty file will cause to print 'null' as output.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class SmallFileReader
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("Demo.txt"));
System.out.println(br.readLine());
}
}
Most examples out there on the web for inputting a file in Java refer to a fixed path:
File file = new File("myfile.txt");
What about a user input file from the console? Let's say I want the user to enter a file:
System.out.println("Enter a file to read: ");
What options do I have (using as little code as possible) to read in a user specified file for processing. Once I have the file, I can convert to string, etc... I'm thinking it has to do with BufferedReader, Scanner, FileInputStream, DataInputStream, etc... I'm just not sure how to use these in conjunction to get the most efficient method.
I am a beginner, so I might well be missing something easy. But I have been messing with this for a while now to no avail.
Thanks in advance.
To have the user enter a file name, there are several possibilities:
As a command line argument.
public static void main(String[] args) {
if (0 < args.length) {
String filename = args[0];
File file = new File(filename);
}
}
By asking the user to type it in:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a file name: ");
System.out.flush();
String filename = scanner.nextLine();
File file = new File(filename);
Use a java.io.BufferedReader
String readLine = "";
try {
BufferedReader br = new BufferedReader(new FileReader( <the filename> ));
while ((readLine = br.readLine()) != null) {
System.out.println(readLine);
} // end while
} // end try
catch (IOException e) {
System.err.println("Error Happened: " + e);
}
And fill the while loop with your data processing.
Regards,
Stéphane
I am getting the all well known FileNotFoundException when i try to call a .txt file that holds some text. I used various path convinations, but i dont get the right one.
Here is how i call it:
private String generateActivationLinkTemplate() {
String htmlText = "";
try {
Scanner scanner = new Scanner(new FileReader(
"/web/emailActivationTemplate.txt"));
while (scanner.hasNextLine()) {
htmlText += scanner.nextLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return htmlText;
}
The full path to the file looks like this:
C:\jee6workspace\BBS\WebContent\web\emailActivationTemplate.txt
How should i tell my program to find this file in the most flexible way?
One way - access to file through servlet context, f.e. i'm use in my Wicket project
final ServletContext ctx = ((WebApplication) getApplication()).getServletContext();
final File reportFile = new File(ctx.getRealPath("/reports/pivotTable.jasper"));
in your case
Scanner scanner = new Scanner(new FileReader(
new File(ctx.getRealPath("/web/emailActivationTemplate.txt"))));
so you only need to get your servlet context in proper place
Other way - try to access to file through classpath.