Question

I do not know why the file I am writing to is blank. I am replacing certain characters and then writing out the new converted file. It should contain all the lines from the file I am importing. However, when I open it, it is completely blank. Thanks.

//this method find the number of occurrences of a character find in a string l
public static int numberOccurances(String l, char find){ 
    int count=0; //sets the number of occurrences to 0
    for(int x=0; x<l.length();x++){ //searches throughout the string adding one to count
        if(l.charAt(x)==find)
        count++;
    }
    return count;
}

public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
    File file = new File("new.txt");
    Scanner scanner = new Scanner(file);
    PrintWriter writer = new PrintWriter("new.txt", "UTF-8");
    while(scanner.hasNextLine()){
        String line = scanner.nextLine();
        for(int y=0; y<line.length(); y++){
            if(line.charAt(y)=='M')
            line=line.substring(0,y) + 'm' + line.substring(y+1);
            if(line.charAt(y)=='m')
            line=line.substring(0,y) + 'M' + line.substring(y+1);
        }
        int numberm=numberOccurances(line, 'm');
        int numberM = numberOccurances(line, 'M');
        line=line + "%:m" + numberm + ":M" + numberM + ":";
        writer.println(line);
    }
    writer.close();
}
Was it helpful?

Solution

You are writing to the same file you are reading from ("new.txt", as per your example). PrintWriter truncates existing files to 0 bytes on opening. Therefore, as soon as you open it, you erase the data in it, and your Scanner has nothing to read.

A traditional approach, when the input and output file are the same, would be to write the output to a new temporary file, and then replace the original file with the temporary file once all processing is complete.

An alternate approach, although far less convenient in your situation, would be to load the input file entirely into memory before opening the output, process the data, then write the processed data out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top