I want to include a test.txt file in my Java program, but I don't know how to include a file in NetBeans for a Java application.
This is my code:
package project;
import java.util.*;
import java.io.*;
import java.io.IOException;
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
new Main().run();
}
public void run()
{
System.out.println("Input String:\n");////
Scanner keyboardScanner = new Scanner(System.in);/////
String inString = keyboardScanner.nextLine();/////
String shortMessage = shortifyMessage(inString);
System.out.println(shortMessage);
}
public String shortifyMessage(String str)
{
String s = str;
String tok1, tok2;
try{
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
String file_name = "C:/textfile.txt";
try {
textfile file = new textfile(file_name);
String[] aryLines = file.OpenFile();
int i;
for (i=0; i<aryLines.length; i++){
System.out.println(aryLines[i]);
}
}
catch (IOException e) {
System.err.format("File Does not exist\n");
}
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
StringTokenizer tokenizer=new StringTokenizer(strLine,"=");
tok1=tokenizer.nextToken();
tok2=tokenizer.nextToken();
//System.out.println(tok1 + " = " + tok2);
if(s.indexOf(tok1)>0)
s = s.replaceAll(tok1, tok2);
//System.out.println (s);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
return s;
}
}
When I run this code it gives the error:
Error: textfile.txt (The system cannot find the file specified)
I don't know how to include the text.txt file so that my code can read the contents of the file and perform appropriate functions.