Java can't read a text file - java

I am trying to read a .txt file and search for a word, but the program just closes with Process finished with exit code 0.
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class LogParser {
static Scanner file;
static ArrayList text = new ArrayList();
static String path = new String();
static String check = new String();
private static int a = 0;
static Scanner inpunt = new Scanner(System.in);
public static void main (String[] args) {
System.out.println("Input path to file");
path = inpunt.nextLine();
File texts = new File(path);
try {
file = new Scanner(new File(path));
} catch (Exception e) {
System.out.println("Can't open file");
}
try {
while (file.hasNext()) {
text.add(a, file.nextLine());
check = text.get(a).toString();
if (check.contains("cap"))
System.out.println("Allert!!!!!!!!!!!!!!!!!!!!!!!!!!!" + text.get(a));
a = a + 1;
}
} catch (Exception e) {
// System.out.println("Can't open file");
if (file.toString().contains("cap"))
System.out.println("cap" + "Path to file: " + path);
System.out.println(text.size());
}
}
}
The text in the .txt file is:
let's try read this cap
If I try to open an xml file, everything is ok. My problem is only in txt files.

As mentioned in the comments, your path variable isn't set. You're trying to create a new file and passing in a path that hasn't been instantiated.

Related

Having issue with getting my file to print to console

I have a data structure assignment were the code has to read the text data from a text file and print it onto the screen. The code that I wrote says that the build was a success but the text file itself doesn't print. What do I do?
import java.util.Scanner;
import java.io.IOException;
import java.io.FileInputStream
public class readFile{
public static void main(String[] args) throws IOException {
FileInputStream fileByteStream = null;
Scanner file = null;
int textFile;
try{
fileByteStream = new FileInputStream("file1.txt");
file = new Scanner(fileByteStream);
while(file.hasNextInt()){
textFile = file.nextInt();
System.out.println("file1.txt");
}
}
catch(IOException e){
}
}
}
Replace System.out.println("file1.txt"); by System.out.println(textFile);.
This should work if you have the "file1.txt" saved in the correct location. As is, you are just passing the String "file1.txt" rather than the file object which was not yet created. (See line 13 of this code below)
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
public class readFile
{
public static void main(String[] args) throws IOException
{
FileInputStream fileByteStream = null;
Scanner file = null;
int textFile;
File file1 = new File("file1.txt");
try
{
fileByteStream = new FileInputStream(file1);
file = new Scanner(fileByteStream);
System.out.println("Reading file...");
while(file.hasNextInt())
{
textFile = file.nextInt();
System.out.println(textFile);
System.out.println("Scanning a line..");
}
file.close();
}
catch(IOException e)
{
System.out.println("Exception handled");
e.printStackTrace();
}
}
}
You can use print statements to help see where the code is breaking. It looks like you have an IO Exception (input/output). Also, you should want to close the Scanner object.
import java.util.Scanner;
import java.io.IOException;
import java.io.FileInputStream;
public class readFile
{
public static void main(String[] args) throws IOException
{
FileInputStream fileByteStream = null;
Scanner file = null;
int textFile;
try
{
fileByteStream = new FileInputStream("file1.txt");
file = new Scanner(fileByteStream);
System.out.println("Reading file...");
while(file.hasNextInt())
{
textFile = file.nextInt();
System.out.println(textFile);
System.out.println("Scanning a line..");
}
file.close();
}
catch(IOException e)
{
System.out.println("Exception handled");
}
}
}

decreasing in size when reversing and storing text from a file to another using Java

I made this homework exercise to read text from a text file and store it reversed into another new file. This is the code:
import java.util.*;
import java.io.*;
public class FileEcho {
File file;
Scanner scanner;
String filename = "words.txt";
File file1 ;
PrintWriter pw ;
void echo() {
try {
String line;
file = new File( filename);
scanner = new Scanner( file );
file1 = new File("brabuhr.txt");
pw = new PrintWriter(file1);
while (scanner.hasNextLine()) {
line = scanner.nextLine();
String s = new StringBuilder(line).reverse().toString();
pw.println(s);
}
scanner.close();
} catch(FileNotFoundException e) {
System.out.println( "Could not find or open file <"+filename+">\n"+e
);
}
}
public static void main(String[] args) {
new FileEcho().echo();
}
}
and here is a picture Picture here
The question is: why is the newly generated file decreased in size despite having the same characters but reversed?
Would be great if someone can explain it because even my professor didn't know why is that.
P.S; the context of the file is just some words from the dictionary.
Also in other students computers so the problem is not from my computer
The problem is that you never closed the output stream pw, so that any pending output isn't written to the underlying file. This may cause truncation of your file.
You should have closed the output stream with pw.close() in a finally, or in a try with resources.
try (pw = new PrintWriter(file1)) {
while (scanner.hasNextLine()) {
line = scanner.nextLine();
String s = new StringBuilder(line).reverse().toString();
pw.println(s);
}
}
Your implementation can be simplified to be the following:
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileEcho {
void echo() throws IOException {
try (PrintWriter pw = new PrintWriter("brabuhr.txt")) {
Files.lines(Paths.get("words.txt"))
.map(s -> new StringBuilder(s).reverse().toString())
.forEach(pw::println);
}
}
public static void main(String[] args) throws IOException {
new FileEcho().echo();
}
}
In this example I used a 'try-with-resources' to have the PrintWriter pw autoclosed.

how to increment number in new file name?

Hi there I am currently writing a method in Java where I am trying to create new files but I need those files not to be of the same name, but rather of incrementing name values, like so:
/Users/Myself/Desktop/myFile0.xml
/Users/Myself/Desktop/myFile1.xml
/Users/Myself/Desktop/myFile2.xml
/Users/Myself/Desktop/myFile3.xml
So I have tried to do the following in my code, but I do not understand why when I call the file within the for each loop ( to create a new one) the number does not increment?
public void pickFolder() throws Exception {
chooserFolder.setDialogTitle("Specify your save location");
chooserFolder.setDialogType(JFileChooser.SAVE_DIALOG);
int numbers = 0;
chooserFolder.setSelectedFile(new File("myFile" + numbers++ + ".xml"));
chooserFolder.setFileFilter(new FileNameExtensionFilter("xml file", "xml"));
int userSelection = chooserFolder.showSaveDialog(null);
if (userSelection == JFileChooser.APPROVE_OPTION) {
for (File file : files) {
chooserFolder.setSelectedFile(new File(chooserFolder.getSelectedFile().getAbsolutePath()));
fileToSave = chooserFolder.getSelectedFile();
if (fileToSave.createNewFile()) {
System.out.println("File is created!");
fileToSave = chooserFolder.getSelectedFile();
} else {
JOptionPane.showMessageDialog(null, "File already exists.");
}
System.out.println("Save as file: " + fileToSave.getAbsolutePath());
}
Any help would be greatly appreciated, Thank you!
What I'm seeing in your code is that you set numbers to ZERO right before incrementing it. try putting int numbers=0 out of your loop if there is any! (you have not written any loop in the code). And of course giving more information would be helpful.
your for-loop has no counter which can be increased, because it is a for-each-loop (if that is the loop you mean). also you call chooserFolder.setSelectedFile(new File("myFile" + numbers++ + ".xml")); only once and there is the only occurrence of numbers++. To given an proper solution you would need to provide all the code. also this line makes no sense at all chooserFolder.setSelectedFile(new File(chooserFolder.getSelectedFile().getAbsolutePath()));. once you give all the code we can provide a solution
Please use the timestamp solution for this problem
String fileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new Date());
Here have a better example below
package com.seleniummaster.examplefile;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CreateFileWithTimeStamp {
public static void main(String[] args)
{
CreateFileWithTimeStamp("test");
}
//Create a new file
public static void CreateFileWithTimeStamp(String filename) {
//get current project path
String filePath = System.getProperty("user.dir");
//create a new file with Time Stamp
File file = new File(filePath + "\\" + filename+GetCurrentTimeStamp().replace(":","_").replace(".","_")+".txt");
try {
if (!file.exists()) {
file.createNewFile();
System.out.println("File is created; file name is " + file.getName());
} else {
System.out.println("File already exist");
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Get current system time
public static String GetCurrentTimeStamp() {
SimpleDateFormat sdfDate = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS");// dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
// Get Current Host Name
public static String GetCurrentTestHostName() throws UnknownHostException {
InetAddress localMachine = InetAddress.getLocalHost();
String hostName = localMachine.getHostName();
return hostName;
}
// Get Current User Name
public static String GetCurrentTestUserName() {
return System.getProperty("user.name");
}
}

Scanner throws FileNotFoundException but using bufferedreader and inputstream doesn't?

I am trying to write code for a word guessing game, and it works well when I use bufferedreader and inputstream combined. But when I try it using scanner, it cannot find the file, even though in both instances the file is in the same folder. It is in a folder called res under the src folder in my project folder(I am coding in eclipse).
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
public class WordGen {
private final String filename = "/res/words.txt";
File file = new File(filename);
Scanner input = null;
private ArrayList<String> list = new ArrayList<>();
public WordGen() {
try {
input = new Scanner(file);
while (input.hasNextLine()) {
String w = input.nextLine();
list.add(w);
}
} catch (Exception ex) {
System.out.println("File not found.");
}
}
public String getword() {
if (list.isEmpty()) {
return "NOTHING";
}
return list.get((int) (Math.random() * list.size()));
}
}
public class test {
public static void main(String[] args) {
WordGen wordgen = new WordGen();
System.out.println(wordgen.getword());
}
}
I tried searching for this problem but couldn't find it here. I am guessing it's a very small error which I cannot figure out. Thanks and regards.
EDIT: Here's the other code that worked(Everything else same as before):
public WordGenerator()
{
try(InputStream input = getClass().getResourceAsStream(fileName);
BufferedReader bfreader = new BufferedReader(new InputStreamReader(input)))
{
String line = "";
while ((line = bfreader.readLine()) != null)
words.add(line);
}
catch (Exception e)
{
System.out.println("Couldn't find file");
}
}
Scanner is trying to load a file - and you're providing an absolute filename, /res/words.txt.
In order to create an InputStream, you're loading a resource, giving it an absolute resource name, even though you've called the variable fileName:
getClass().getResourceAsStream(fileName)
That works because it can load a resource called /res/words.txt from the classpath, but it's not loading a file with a filename of /res/words.txt.
You could use a filename of res/words.txt, if you run the code from the src directory... or you could just stick to using getResourceAsStream, which is probably a better idea as it doesn't rely on your working directory, and will continue to work even if your code and resources are packaged up into a jar file.
If you really want to use Scanner, you could always use new Scanner(input) - there's a Scanner constructor accepting an InputStream.

Java .jar fails to start because of loading jcombobox data from file

I am beginner with Java and I have tried to make my app better.
So I have a method to fill the jcombobox with items from text file.
The method is
private void fillComboBox(JComboBox combobox, String filepath) throws FileNotFoundException, IOException {
BufferedReader input = new BufferedReader(new FileReader(filepath));
List<String> strings = new ArrayList<String>();
try {
String line = null;
while ((line = input.readLine()) != null) {
strings.add(line);
}
} catch (FileNotFoundException e) {
System.err.println("Error, file " + filepath + " didn't exist.");
} finally {
input.close();
}
String[] lineArray = strings.toArray(new String[]{});
for (int i = 0; i < lineArray.length - 1; i++) {
combobox.addItem(lineArray[i]);
}
}
And I am using it correctly
fillComboBox(jCombobox1, "items");
the text file with items is in my root directory of netbeans project.
It works perfectly when running the app from netbeans. But when I build the project and create .jar file. It does not run. I tried to run it from comand line.
This is what I got.
java.io.FileNotFoundException: items(System cannot find the file.)
How to deal with this? I didnt found anything. I dont know where is problem since it works nice in netbeans. Thank you very much for any help.
Is the .jar file in the same root directory?
Your exported .jar file might be working from a different directory, and not be able to find the text file.
Try placing the exported Jar in the same directory as the text file.
My example:
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
public class test {
public static void main(String[] args) throws FileNotFoundException, IOException{
JComboBox box = new JComboBox();
fillComboBox(box, "C:\\path\\test.txt");
JOptionPane.showMessageDialog(null, box);
}
private static void fillComboBox(JComboBox combobox, String filepath) throws FileNotFoundException, IOException {
BufferedReader input = new BufferedReader(new FileReader(filepath));
List<String> strings = new ArrayList<String>();
try {
String line = null;
while ((line = input.readLine()) != null) {
strings.add(line);
}
} catch (FileNotFoundException e) {
System.err.println("Error, file " + filepath + " didn't exist.");
} finally {
input.close();
}
String[] lineArray = strings.toArray(new String[] {});
for (int i = 0; i < lineArray.length - 1; i++) {
combobox.addItem(lineArray[i]);
}
}
}

Categories