In the below program, I have to first read a file and then write it. In the run configurations I provided the path of the file but when I run the program then it gives error: String index out of range: -1. ? Please help
public static void main(String[] args) throws IOException{
String fileName = args[0];
Scanner filescan;//to read the file
filescan=new Scanner(new File(fileName));//read the whole file
FileWriter fstream = new FileWriter(fileName.subSequence(0,fileName.indexOf(".uniqe.ICext"))+".uniqe.Mpwm");
BufferedWriter mpwm = new BufferedWriter(fstream);
you should add validations before use substring. otherwise it will eventually throw an Exception
int i= fileName.indexOf(".uniqe.ICext");
if(i<0)
//file name can't substring or handle exception
else
FileWriter fstream = new FileWriter(fileName.subSequence(0,i)+".uniqe.Mpwm");
Related
Alright so to get straight to the point I've coded a simple application in which it gets the string of the first line of the files it goes through and then I make it to log all the strings it gets to a txt file but when it logs it just continues to replace itself with the new strings in the other files.
I want it to log the strings it gets then write the new string from the other file in a new line but I cannot seem to make it work.
To anyone who can help me fix this I'd really appreciate it.
public static void main(String[] args) throws Exception {
File dir = new File("C://Users//Test//Desktop//lists");
if (dir.isDirectory()) {
for (File file : dir.listFiles()) {
String line1 = Files.readAllLines(Paths.get(file.getAbsolutePath())).get(0);
BufferedWriter writer = new BufferedWriter(new FileWriter("C://Users//Test//Desktop//logged.txt"));
writer.write(line1);
writer.newLine();
writer.close();
}
}
}
Note :
you must open and close the writer object, outside of for loop
Try this
public static void main(String[] args) throws Exception {
File dir = new File("C://Users//Test//Desktop//lists");
if (dir.isDirectory()) {
BufferedWriter writer = new BufferedWriter(new FileWriter("C://Users//Test//Desktop//logged.txt"));
for (File file : dir.listFiles()) {
String line1 = Files.readAllLines(Paths.get(file.getAbsolutePath())).get(0);
writer.write(line1);
writer.newLine();
}
writer.close();
}
}
You are reopening the file logged.txt in each iteration of your text loop. This will truncate the file and start writing at the beginning again. If you really want to reopen the file, you need to use append mode: FileWriter("filename.txt", true), but you probably want to open the BufferedWriter before your loop and close it afterwards.
You new your writer every time. Add the new line before the for begins.
public static void main(String[] args) throws Exception {
File dir = new File("C://Users//Test//Desktop//lists");
if (dir.isDirectory()) {
BufferedWriter writer = new BufferedWriter(new FileWriter("C://Users//Test//Desktop//logged.txt"));
for (File file : dir.listFiles()) {
String line1 = Files.readAllLines(Paths.get(file.getAbsolutePath())).get(0);
writer.write(line1);
writer.newLine();
}
writer.close();
}
}
I am using java.net.DatagramPacket to trans file. I have some code below
public void sendFile(InetAddress clientHost, int clientPort, String fileName) throws IOException {
String filePath = "e:\\uri\\" + fileName;
System.out.println(filePath);
FileInputStream inputFile = new FileInputStream(filePath);
}
I have a folder uri in and do create file.txt first. While debuging this, this is what shows up in console:
e:\uri\file.txt
java.io.FileNotFoundException: Invalid file path
at java.io.FileInputStream.<init>(FileInputStream.java:133)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at MyFileServerSocket.sendFile(MyFileServerSocket.java:19)
at FiletransServer.main(FiletransServer.java:22)
I found something more interesting that i can see the value of fileName in eclipse and it's strange.
There is extra quotation marks in there and the string printed in the console is normal. No idea why.
I suppose fileName you've passed into sendFile(...) has illegal characters. Please check it thoroughly and you should try hardcode filePath something like this and try once again:
public void sendFile(InetAddress clientHost, int clientPort, String fileName) throws IOException {
// Hardcode file.txt
String filePath = "e:\\uri\\file.txt";
// Print fileName surrounded with quoutes
System.out.printf("'%s'", fileName);
FileInputStream inputFile = new FileInputStream(filePath);
}
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 take a word as input and check whether that word is present in a text file. But I ended up with this error.
import java.io.*;
public class SpellingChecker {
public static void test(String str) throws IOException{
FileReader fr = new FileReader("wordsEn.txt");
BufferedReader br = new BufferedReader(fr);
int i=0,j=0,n=str.length();
str+=' ';
String temp="",temp2="";
do{
for(i=j;str.charAt(i)!=' ';i++)
temp+=str.charAt(i);
System.out.println(temp);
while((temp2=br.readLine()) != null) {
if(temp==temp2)
System.out.print("\t\t\tOK");
else
System.out.print("\t\t\tWRONG");
}
temp="";
j=i+1;
}while(i<n);
fr.close();
}
public static void main(String[] args) throws IOException{
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter string for which you want to check spelling : ");
String strng=input.nextLine();
test(strng);
}
}
Error is
Exception in thread "main" java.io.FileNotFoundException: wordsEn.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:131)
at java.io.FileInputStream.<init>(FileInputStream.java:87)
at java.io.FileReader.<init>(FileReader.java:58)
at SpellingChecker.test(SpellingChecker.java:5)
at SpellingChecker.main(SpellingChecker.java:29)
Only the name of the file will not do.You have to mention the path of the file while creating
the "FileReader" object.For example,if the path is "C:\wordsEn.txt",you should write:-
FileReader fr=new FileReader(new File("C://wordsEn.txt"));
Remember,if you use '\' in place of "//" "Illegal Escape Character" will be the error shown.
This should fix it.Give it a try...
You have to put your text file in the source directory.
I've been working on a small project in Java. The program writes to a log file from different methods . But each time a method is used , the content of the file gets deleted and all what's written in it is the result of the last method.
here's a code snippet of the program :
// dir , log_file , exp_date and amount are declared in the code removed
public static void WriteHeader() throws IOException
{
FileWriter fileWriter = new FileWriter(dir+"/"+log_file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
Console console = System.console();
exp_date = console.readLine("Enter a string here: ");
bufferedWriter.write(exp_date);
bufferedWriter.close();
}
public static void WriteNewLine() throws IOException
{
FileWriter fileWriter = new FileWriter(dir+"/"+log_file);
BufferedWriter bufferedWriter2 = new BufferedWriter(fileWriter);
Console console = System.console();
amount = console.readLine("Enter another string here :");
bufferedWriter2.newLine();
bufferedWriter2.write(amount);
bufferedWriter2.close();
}
You need to create the writer in append mode http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter(java.io.File, boolean)
You need to open file in append mode otherwise once you close the file and reopen it to write, it would erase previous data. http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter(java.lang.String, boolean)
FileWriter fileWriter = new FileWriter(dir+"/"+log_file, true);
FileWriter fw = new FileWriter(file, true);
I am pretty sure FileWriter has an overloaded constructor for appending to a file instead of overwriting a file
I would also check if the file exists first.
file.exists();